Trapping an Exception with catch

The other way to trap an exception is to use the primitive catch. The catch primitive is not the same as the catch block in the try...catch statement (this is because the catch statement was part of the language long before try...catch was introduced).

When an exception occurs within a catch statement, it is converted into an {’EXIT’, ...} tuple that describes the error. To demonstrate this, we can call generate_exception within a catch expression.

try_test.erl
 
demo2() ->
 
[{I, (​catch​ generate_exception(I))} || I <- [1,2,3,4,5]].

Running this we obtain the following:

 
2>​ try_test:demo2().
 
[{1,a},
 
{2,a},
 
{3,{'EXIT',a}},
 
{4,{'EXIT',a}},
 
{5,{'EXIT',
 
{a,[{try_test,generate_exception,1,
 
[{file,"try_test.erl"},{line,9}]}, ...

Get Programming Erlang, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.