O'Reilly logo

Real World OCaml by Jason Hickey, Anil Madhavapeddy, Yaron Minsky

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 7. Error Handling

Nobody likes dealing with errors. It’s tedious, it’s easy to get wrong, and it’s usually just not as fun as planning out how your program is going to succeed. But error handling is important, and however much you don’t like thinking about it, having your software fail due to poor error handling is worse.

Thankfully, OCaml has powerful tools for handling errors reliably and with a minimum of pain. In this chapter we’ll discuss some of the different approaches in OCaml to handling errors, and give some advice on how to design interfaces that make error handling easier.

We’ll start by describing the two basic approaches for reporting errors in OCaml: error-aware return types and exceptions.

Error-Aware Return Types

The best way in OCaml to signal an error is to include that error in your return value. Consider the type of the find function in the List module:

OCaml utop

# List.find;;
- : 'a list -> f:('a -> bool) -> 'a option = <fun>

The option in the return type indicates that the function may not succeed in finding a suitable element:

OCaml utop (part 1)

# List.find [1;2;3] ~f:(fun x -> x >= 2) ;;
- : int option = Some 2
# List.find [1;2;3] ~f:(fun x -> x >= 10) ;;
- : int option = None

Including errors in the return values of your functions requires the caller to handle the error explicitly, allowing the caller to make the choice of whether to recover from the error or propagate it onward.

Consider the compute_bounds function. The function takes a list and a comparison ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required