typestar

Exceptions in OCaml

Declared like variants, caught by pattern.

(* Exceptions declare like variants; try/with catches by pattern. *)
exception Pool_closed of string

let open_pool name =
  if name = "cove" then raise (Pool_closed "nesting birds")
  else name ^ " open for sampling"

let attempt name =
  try open_pool name with
  | Pool_closed reason -> name ^ " skipped: " ^ reason

let () =
  print_endline (attempt "north");
  print_endline (attempt "cove");
  (* Failure is the stock exception failwith raises. *)
  (try failwith "tide turned" with
   | Failure msg -> Printf.printf "Called off: %s\n" msg)

How it works

  1. exception Pool_closed of string declares with a payload.
  2. try ... with | Pool_closed reason -> catches by shape.
  3. failwith raises the stock Failure exception.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
527
Tokens
92
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 85 seconds.

Type this snippet

Step 2 of 3 in Idioms, step 25 of 29 in Language basics.

← Previous Next →

Exceptions in other languages