Benefits of OCaml

Exceptions

In order to write reliable programs, the ability to handle unexpected circumstances in a controlled manner is essential. OCaml provides an exception mechanism where exceptions can be raised and subsequently caught. Exceptions can also carry data.

Exceptions are defined using the exception keyword:

# exception Foo;;
exception Foo

# exception Bar of string;;
exception Bar of string

raised using the raise keyword:

# raise (Failure "Fooey");;
Exception: Failure "Fooey".

and caught using the using the try ... with ... construct:

# try
    raise Not_found
  with
    Not_found ->
      print_endline "Didn't find it";;
Didn't find it
- : unit = ()

Note that OCaml predefines some exceptions, including Not_found, Failure, Invalid_argument and End_of_file.

Exceptions allow programs to handle unexpected occurrences in a reliable and predictable manner.