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
exception Pool_closed of stringdeclares with a payload.try ... with | Pool_closed reason ->catches by shape.failwithraises the stockFailureexception.
Keywords and builtins used here
FailurePool_closedelseexceptionifletofraisestringthentrywith
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.
Step 2 of 3 in Idioms, step 25 of 29 in Language basics.