Programming Style with Exceptions

Handling exceptions is not rocket science; the following sections contain some frequently occurring code patterns that we can reuse in our programs.

Improving Error Messages

One use of the error/1 BIF is to improve the quality of error messages. If we call math:sqrt(X) with a negative argument, we’ll see the following:

 
1>​ math:sqrt(-1).
 
** exception error: bad argument in an arithmetic expression
 
in function math:sqrt/1
 
called as math:sqrt(-1)

We can write a wrapper for this, which improves the error message.

lib_misc.erl
 
sqrt(X) ​when​ X < 0 ->
 
error({squareRootNegativeArgument, X});
 
sqrt(X) ->
 
math:sqrt(X).
 
2>​ lib_misc:sqrt(-1).
 
** exception error: {squareRootNegativeArgument,-1}
 
in function ...

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.