Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 40 ยท Imperative Features and Exceptions

Exceptions: raise, try, Custom Exceptions and Cleanup

Learn how OCaml exceptions work. Raise and catch them, define your own with data, use match with exception, clean up with Fun.protect, and decide when exceptions beat result types.

An exception is a value that interrupts normal evaluation and travels up the call stack until a handler catches it. OCaml uses exceptions for situations such as "key not found", "invalid argument", "end of file" and "division by zero". They are cheap, much cheaper than in most languages, which is why the standard library and idiomatic code use them for control flow as well as errors.

OCaml is not available in the site's code runners, so the ocaml blocks are read-only. Printed results are shown only where they are certain. The Python stand-ins show the same control flow.

Raising and catching

OCAML
let safe_div a b =
  if b = 0 then raise Division_by_zero else a / b

let () =
  try
    Printf.printf "%d\n" (safe_div 10 0)
  with
  | Division_by_zero -> print_endline "cannot divide by zero"
(* prints: cannot divide by zero *)

try expr with | pattern -> handler evaluates expr; if it raises, the handlers are tried as patterns against the exception. If none matches, the exception continues upward. The handler must have the same type as the try body.

Common built-in exceptions:

Exception Raised by
Not_found List.find, Hashtbl.find, List.assoc
Invalid_argument msg array index out of bounds, String.sub with bad range, invalid_arg
Failure msg failwith "msg", int_of_string "x", List.hd []
Division_by_zero integer / and mod by zero
End_of_file reading past the end of a channel
Stack_overflow, Out_of_memory resource exhaustion

failwith "message" raises Failure "message", and invalid_arg "message" raises Invalid_argument.

Defining your own

OCAML
exception Parse_error of string
exception Out_of_range of { value : int; max : int }

let parse_digit c =
  if c >= '0' && c <= '9' then Char.code c - Char.code '0'
  else raise (Parse_error (Printf.sprintf "not a digit: %c" c))

let check n =
  if n > 100 then raise (Out_of_range { value = n; max = 100 }) else n

Exceptions are values of the built-in extensible type exn, and exception E of ... adds a new constructor to it. They can carry data, including inline records.

OCAML
let () =
  match parse_digit 'x' with
  | d -> Printf.printf "digit %d\n" d
  | exception Parse_error msg -> Printf.printf "error: %s\n" msg
(* prints: error: not a digit: x *)

match with exception

match ... with | exception E -> ... handles the normal result and the exceptions in one expression, with the benefit that only the scrutinee is protected. In a plain try, every exception raised anywhere in the body is a candidate for the handlers, including ones from the code that processes the result. Compare:

OCAML
(* risky: a Not_found raised by (process v) is also caught *)
let r1 = try process (Hashtbl.find tbl k) with Not_found -> default

(* precise: only the lookup is guarded *)
let r2 =
  match Hashtbl.find tbl k with
  | v -> process v
  | exception Not_found -> default

Prefer the second form. Better still, use Hashtbl.find_opt and match on the option.

Re-raising and handlers that do not match

OCAML
let with_logging f =
  try f () with
  | e ->
      prerr_endline ("failed: " ^ Printexc.to_string e);
      raise e

A catch-all | e -> ... handles everything, including Out_of_memory and Stack_overflow, so catch broad patterns only to log and re-raise. To keep the original backtrace when re-raising in OCaml 4.x and 5, use Printexc.get_raw_backtrace and Printexc.raise_with_backtrace, or run with OCAMLRUNPARAM=b while debugging to see where an uncaught exception came from.

Cleanup with Fun.protect

Resources need releasing whether the code succeeds or fails. Fun.protect ~finally is OCaml's finally:

OCAML
let read_first_line path =
  let ic = open_in path in
  Fun.protect
    ~finally:(fun () -> close_in_noerr ic)
    (fun () -> input_line ic)

The file is closed even if input_line raises End_of_file. Many libraries offer with_ helpers built on this pattern, such as In_channel.with_open_text in the standard library:

OCAML
let first_line path = In_channel.with_open_text path In_channel.input_line
(* returns string option *)

Exceptions as control flow

A local exception gives you a break:

OCAML
exception Found of int

let first_negative xs =
  try
    List.iter (fun x -> if x < 0 then raise (Found x)) xs;
    None
  with Found x -> Some x

Because the exception is declared locally to the function and caught in it, callers never see it. Raising is cheap (no stack trace is built unless backtraces are on), which makes this pattern common in search and parsing code.

Exceptions versus result

flowchart TD
    Q["Can the caller reasonably recover?"] -->|"yes, and it is expected"| R["return option or result"]
    Q -->|"no, it is a bug or an emergency"| E["raise an exception"]
    Q -->|"internal early exit"| L["local exception"]

Figure: a rule of thumb for choosing the error style.

A function that can fail should make that visible in its type (option and result). Exceptions stay appropriate for programmer errors (invalid_arg), impossible states and non-local exits. Whichever you choose, document it and be consistent.

A bridge between the two: Result.try-style helpers are easy to write:

OCAML
let try_with f = try Ok (f ()) with e -> Error e

Stand-in: raise, catch and finally in Python

Python Stand-in: custom exception, handler and cleanup

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Common mistakes

  • Writing | _ -> ... in a handler and swallowing bugs and Out_of_memory.
  • Wrapping too much code in try, so that an unrelated exception is caught by the wrong handler.
  • Forgetting that try ... with handlers return the same type as the body.
  • Letting Not_found escape from deep inside code. It carries no message, so catch it near the source or use the _opt function.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does exception Parse_error of string do?

    Exceptions are constructors of the built-in type exn, and this line adds one.
  2. 2. Why is match f x with | v -> ... | exception Not_found -> ... more precise than try?

    Exceptions raised while processing v are not caught by the exception arm.
  3. 3. Which function guarantees a cleanup action runs even if the body raises?

    Fun.protect runs the finally function after the body, on success or failure.
  4. 4. When should a function return result instead of raising?

    Putting expected failures in the type makes them visible and checked by the compiler.

Summary

  • Exceptions are values of type exn; raise throws and try ... with or match ... with exception catches by pattern.
  • Define your own with exception E of ... and use local exceptions for early exits.
  • Use Fun.protect ~finally to release resources.
  • Prefer option and result for expected failures. Reserve exceptions for bugs, emergencies and non-local exits.

Next: Input, Output and Formatting