Exceptions: try and catch
| throw, error, exit | |
| try ... catch | |
| Why catch | |
| The after clause |
throw, error, exit
Three kinds of exceptions exist. throw carries any value, error carries an error term, and exit carries an exit reason between processes.
The runtime also raises errors itself: a bad match, a bad argument, or a missing key all arrive as errors.
1> throw(my_error).
** exception throw: my_error
2> error(bad_arg).
** exception error: bad_arg
3> exit(reason).
** exception exit: reason
try ... catch
The try expression catches exceptions by class. Each catch line names the class, binds the reason, and runs its body when a matching exception arrives.
Catch only the classes you can handle, and let the rest escape to the supervisor.
try
dangerous()
catch
error:Why -> {error, Why};
throw:What -> {thrown, What}
end.
Why catch
Expected failures travel as {error, Reason} tuples, not exceptions. Reserve try for the rare places where a crash is genuinely part of the flow, such as parsing untrusted input.
A caught exception inside a hot loop is slower than a plain match, so the ok tuple stays the default.
safe_divide(A, B) ->
try A / B
catch error:badarith -> {error, not_a_number}
end.
The after clause
The after clause runs whether the try body succeeds, fails, or throws. Use it to release a file, a socket, or an ETS table handle.
The after body cannot change the result of the try, only clean up around it.
try
work(Handle)
after
close(Handle)
end.
Next: Modules, exports and imports
Article author: Arthur Isaev