September 2013
Intermediate to advanced
548 pages
12h 25m
English
Handling exceptions is not rocket science; the following sections contain some frequently occurring code patterns that we can reuse in our programs.
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 ... |
Read now
Unlock full access