TExcelTAD
Home › OCaml › OCaml Exceptions

OCaml Exceptions

An exception interrupts normal evaluation and jumps to the nearest handler. OCaml uses exceptions for errors that are unusual or that the immediate caller cannot sensibly handle. They are also very fast, so they are sometimes used for control flow, such as leaving a loop early.

Raising and catching

raise throws an exception. try expr with pattern -> handler catches it:

ocaml · try it yourself
let average lst =
  if lst = [] then raise (Invalid_argument "average: empty list")
  else float (List.fold_left ( + ) 0 lst) /. float (List.length lst)

let report lst =
  try Printf.printf "average %.2f\n" (average lst)
  with Invalid_argument msg -> Printf.printf "error: %s\n" msg

let () =
  report [ 3; 4; 8 ];
  report []
average 5.00
error: average: empty list

The handler is a pattern match on the exception, so you can handle several kinds with several branches. Both the try body and the handlers must have the same type.

Built-in exceptions

Exception Raised by
Not_found List.find, List.assoc, Hashtbl.find, Map.find, String.index
Invalid_argument of string List.nth (negative index), String.sub, array bounds, invalid_arg
Failure of string int_of_string, List.hd [], failwith
Division_by_zero integer / or mod by 0
Exit free for your own use, to leave a loop
End_of_file reading past the end of input
Match_failure, Assert_failure a non-exhaustive match, a failed assert
Stack_overflow, Out_of_memory resource exhaustion

failwith msg is shorthand for raise (Failure msg) and invalid_arg msg for raise (Invalid_argument msg).

ocaml · try it yourself
let try_it label f =
  match f () with
  | n -> Printf.printf "%-10s ok %d\n" label n
  | exception Not_found -> Printf.printf "%-10s Not_found\n" label
  | exception Division_by_zero -> Printf.printf "%-10s Division_by_zero\n" label
  | exception Failure msg -> Printf.printf "%-10s Failure %S\n" label msg
  | exception Invalid_argument msg -> Printf.printf "%-10s Invalid_argument %S\n" label msg

let () =
  try_it "find" (fun () -> List.find (fun x -> x > 5) [ 1; 2 ]);
  try_it "divide" (fun () -> 10 / 0);
  try_it "hd" (fun () -> List.hd []);
  try_it "parse" (fun () -> int_of_string "1e");
  try_it "sub" (fun () -> String.length (String.sub "abc" 2 5));
  try_it "fine" (fun () -> 6 * 7)
find       Not_found
divide     Division_by_zero
hd         Failure "hd"
parse      Failure "int_of_string"
sub        Invalid_argument "String.sub / Bytes.sub"
fine       ok 42

This example also shows the match ... with exception form: it matches either the normal result or an exception in one expression. It is often clearer than try, especially because the normal-result branch is outside the handler.

Defining exceptions

Declare your own exceptions with exception Name or exception Name of type:

ocaml · try it yourself
exception Insufficient_stock of string * int   (* item, how many are available *)
exception Unknown_item of string

let inventory = [ ("bolt", 40); ("nut", 3) ]

let take item qty =
  match List.assoc_opt item inventory with
  | None -> raise (Unknown_item item)
  | Some available when available < qty -> raise (Insufficient_stock (item, available))
  | Some available -> available - qty

let order item qty =
  try Printf.printf "order %d %s: %d left\n" qty item (take item qty) with
  | Insufficient_stock (name, n) -> Printf.printf "order %d %s: only %d available\n" qty name n
  | Unknown_item name -> Printf.printf "order %s: no such item\n" name

let () =
  order "bolt" 10;
  order "nut" 5;
  order "gear" 1
order 10 bolt: 30 left
order 5 nut: only 3 available
order gear: no such item

Cleanup with Fun.protect

To run cleanup code whether or not an exception happens (like finally in other languages), use Fun.protect ~finally:

ocaml · try it yourself
let with_resource name f =
  Printf.printf "open %s\n" name;
  Fun.protect ~finally:(fun () -> Printf.printf "close %s\n" name) (fun () -> f name)

let () =
  with_resource "log.txt" (fun n -> Printf.printf "writing to %s\n" n);
  try with_resource "data.csv" (fun _ -> failwith "disk full")
  with Failure msg -> Printf.printf "caught: %s\n" msg
open log.txt
writing to log.txt
close log.txt
open data.csv
close data.csv
caught: disk full

Uncaught exceptions and assertions

An exception that nobody catches ends the program with Fatal error: exception ... and exit code 2. assert cond raises Assert_failure (with the file and line) when cond is false; use it for "this can never happen" checks:

ocaml · try it yourself
exception Config_error of string

let () =
  assert (1 + 1 = 2);
  print_endline "starting";
  raise (Config_error "missing PORT")
starting
Fatal error: exception Example.Config_error("missing PORT")

Exceptions you define are printed with the name of the module they belong to. The playground compiles your code as a file called example.ml, so the module is Example.

Exceptions or results?

Exceptions are not visible in a function's type, so callers can forget to handle them. For failures that are a normal part of the domain (bad user input, a missing file), prefer option or result. Keep exceptions for bugs and truly exceptional situations, and catch them close to where they are raised.

Test yourself

What does failwith "oops" raise?

  1. Exit
  2. Failure "oops"
  3. Invalid_argument "oops"
  4. Error "oops"

How do you declare an exception carrying an int?

  1. exception Too_big : int
  2. exception Too_big of int
  3. type Too_big = exception int
  4. raise Too_big of int

Which construct runs cleanup code even when an exception escapes?

  1. try ... with _ -> ()
  2. Fun.protect ~finally
  3. ignore
  4. assert