Handling Errors in Sequential Code
Every time we call a function in Erlang, one of two things will
happen: either the function returns a value or something goes
wrong. We saw examples of this in the previous chapter. Remember
the cost
function?
shop.erl | |
| cost(oranges) -> 5; |
| cost(newspaper) -> 8; |
| cost(apples) -> 2; |
| cost(pears) -> 9; |
| cost(milk) -> 7. |
This is what happened when we ran it:
| 1> shop:cost(apples). |
| 2 |
| 2> shop:cost(socks). |
| ** exception error: no function clause matching |
| shop:cost(socks) (shop.erl, line 5) |
When we called cost(socks)
, the function crashed. This
happened because none of the clauses that define the function
matched the calling arguments.
Calling cost(socks)
is pure nonsense. There is no sensible value that the ...
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.