Exceptions: try and catch
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.
erl
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.
-module(attempt).
-export([run/1]).
run(F) ->
try F()
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.
-module(safe).
-export([divide/2]).
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.
-module(cleanup).
-export([run/1]).
run(F) ->
try F()
after
io:format("cleanup~n")
end.
erlc attempt.erl
erlc safe.erl
erlc cleanup.erl
erl
1> attempt:run(fun() -> throw(oops) end).
{thrown,oops}
2> attempt:run(fun() -> error(bad) end).
{error,bad}
3> attempt:run(fun() -> 42 end).
42
4> safe:divide(6, 3).
2.0
5> safe:divide(1, 0).
{error,not_a_number}
6> cleanup:run(fun() -> ok end).
cleanup
ok
Next: Modules, exports and imports
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which three classes of exception does Erlang have?
Answer
throw,error,exitthrowcarries a value,errorcarries an error term, andexitcarries a reason between processes. -
What does
throw(my_error).print in the shell?Answer
** exception throw: my_errorAn uncaught throw is reported with its class and the value it carries.
-
What does
error(bad_arg).raise?Answer
An error with the reason
bad_argerror/1raises an error whose reason is the given term. -
What does
exit(reason).carry?Answer
A value between processes
The exit class carries a reason, usually between processes.
-
Which clause handles a
throwintry F() catch error:Why -> ...; throw:What -> ... end.?Answer
The
throwclauseA catch clause names its class, so a throw reaches the
throwline. -
What does
attempt:run(fun() -> 42 end).return?Answer
42The fun returns normally, so the try body returns 42 and no catch clause runs.
-
What does
safe:divide(1, 0).return?Answer
{error,not_a_number}Division by zero raises
badarith, and the catch clause turns it into an error tuple. -
When does an
afterclause run?Answer
Whether the body succeeds, fails, or throws
afteralways runs, which is what makes it useful for releasing a handle. -
What can an
afterclause change about the result?Answer
Nothing: it only cleans up
The
afterbody runs around the try and cannot replace its result. -
Why does the lesson prefer the ok tuple for expected failures?
Answer
It keeps the normal flow fast and explicit
A plain match is cheaper than a caught exception, and the caller must handle the error value.
The examples on this page were compiled and run with Erlang/OTP 27 (erts-15.2.7.14) on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev