11 Exceptions

Exceptions are extensible variants.

type exn

You can define your own exception with the keyword exception. This is just a constructor for exn.

exception ABadThing
exception OhNo of string

Type exn is a built-in extensible variant. It allows us to provide constructors later.

Here we created an exception called OhNo that carries type string We can create an exception now with our OhNo constructor:

Note that we now have a value of type exn! We can use the raise function to "throw" an exception:

Look at that! There's been an exception, the same way that if we were to divide by zero!

Exceptions don't need to carry any data:

OCaml programmers are more likely to create their own exceptions than Java programmers, just because it is so easy to do so. The built in function raise has type exn -> 'a.

What's interesting is that raise has a return type of 'a. We can treat it as any type we want because it never will actually return.

Note that the error we got here was ABadThing, not a type error. This is because the type system was okay with our work, because raise will never actually return.

OCaml provides some predefined exceptions that are used pretty often

is the same as