Cover by Francesco Cesarini, Simon Thompson

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

Handling Errors

In the preceding section, you saw some of the errors that can occur in an Erlang system, together with diagnoses of the potential causes.

When executing an expression and a runtime error occurs, you might want to catch the exception and prevent the thread of execution from terminating. Alternatively, you might want to let it fail and for some other part of the system deal with recovery: this latter option, which involves process linking and supervision, will be covered in Chapters 6 and 12. In the meantime, in this section we will discuss how errors can be caught and handled, using the try ... catch construct.

Using try ... catch

The idea behind the try ... catch construct is to evaluate an expression, and providing ways of handling the normal result of the expression as well as abnormal termination. What’s more, the construct allows you to differentiate between different return values that arise as a result of Erlang’s different exception-handling mechanisms, and to handle them in different ways.

Before the expression to be evaluated, you insert the reserved word try. You pattern-match the (normal) result as you would have done in a case statement, but instead of terminating the clauses with an end, you replace it with a catch followed by clauses to handle exceptions. These clauses have an exception type (also called classes) and exception patterns at their head, and corresponding return expressions.

The try ... catch construct has the following form:

try Exprs of
   Pattern1 ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required