OCaml has an exception mechanism similar to many other programming languages. A new type of OCaml exception is defined with this syntax:
| |
To create an exception value, use the same syntax you would for creating a variant value. Here, for example, is an exception value whose constructor is Failure, which carries a string:
| |
To catch an exception, use this syntax:
| |
The expression e is what might raise an exception. If it does not, the entire try expression evaluates to whatever e does. If e does raise an exception value v, that value v is matched against the provided patterns, exactly like match expression.
Pattern Matching
There is a pattern form for exceptions. Here’s an example of its usage:
| |
Exception patterns are a kind of syntactic sugar. Consider this code for example:
| |
We can rewrite the code to eliminate the wxception pattern:
| |
In general if there are both exception and non-exception patterns, evaluation proceeds as follows:
- Try evaluating
e. If it produces an exception packet, use the exception patterns from the original match expression to handle that packet. - If it doesn’t produce an exception packet but instead produces a non-exception value, use the non-exception patterns from the original match expression to match that value.