Lesson 6 of 9 · 25m
Errors, IO, and Effects in Real Programs
Choose between exceptions, result values, and effect handlers deliberately while keeping IO boundaries explicit and testable.
The dangerous part of production ML is rarely pure evaluation. It is the boundary: network calls, file handles, database transactions, user input, clocks, randomness, and concurrency. OCaml gives you several ways to represent failure. Picking one carelessly is how a beautiful typeful core gets surrounded by exception spaghetti.
Exceptions are for exceptional control flow
OCaml exceptions are real control-flow mechanisms, not just error values:
exception Missing_config of string
let require_env name =
match Sys.getenv_opt name with
| Some value -> value
| None -> raise (Missing_config name)Use them for invariant violations, programmer mistakes, or genuinely exceptional control paths. They are poor as the primary representation of routine business failure because the type of a function does not say which exceptions it may raise.
Result values make failure part of the contract
type config_error = Missing of string | Invalid of string * string
let parse_port value =
match int_of_string_opt value with
| Some port when port > 0 && port < 65536 -> Ok port
| _ -> Error (Invalid ("PORT", value))Ok and Error force callers to confront failure. Projects often define let ( let* ) = Result.bind so sequential parsing can propagate errors without a staircase of matches.
IO should live at the edge
A maintainable OCaml service usually separates pure domain decisions from effectful adapters:
pure core: validates commands, transforms state, decides needed effects
effectful shell: files, sockets, database calls, responses, telemetryThat separation is not functional-programming decoration. It is test strategy. A pure decision function can be exhaustively tested without network fixtures; a thin shell can be tested with integration tests.
Lwt, Async, and direct-style concurrency are ecosystems
Historically, concurrent OCaml splits between Lwt and Async, each with its own monadic style. OCaml 5 introduced domains and effect handlers, enabling direct-style concurrency libraries without callback-shaped application code. Before adopting a concurrency library, decide which ecosystem your dependencies already use. Mixing models casually creates awkward translation layers and subtle lifecycle bugs.
Cancellation and resource cleanup are the real tests
Use Fun.protect or library equivalents around resources:
let with_channel path f =
let ic = open_in_bin path in
Fun.protect ~finally:(fun () -> close_in_noerr ic) (fun () -> f ic)Failure behavior under cancellation matters more than happy-path syntax. Ask what closes, what rolls back, what logs, and what remains partially written.
Field notes
raise_notracecan preserve performance in hot paths but removes useful backtraces; use it only when the distinction is understood.- Enable backtraces during development with
OCAMLRUNPARAM=bor equivalent runtime configuration. failwithis convenient in prototypes and unhelpful in production because it erases structured error identity.- An error type shared across every layer becomes a coupling point. Translate domain errors at module boundaries.
Was this lesson helpful?