Exceptions: try and catch

An Erlang function has two ways to report a problem: it returns a value such as {error, Reason}, or it raises an exception. The first is the normal path and the caller must look at it; the second stops the function where it stands and lets a handler further up decide. This lesson covers the three classes of exception, the try ... catch ... after expression that handles them, and the catch-all clause that makes a program look healthy while it is wrong.

throw, error, exit

Every exception has a class and a reason. error is the class the runtime uses for a broken call: a bad argument, an arithmetic error, a match that does not fit. throw carries any term and is meant for a non-local return that the program itself controls. exit carries a reason between processes, and the runtime raises it when the process is told to stop. The shell prints the class and the reason of an exception that nobody caught:

erl

1> throw(my_error). ** exception throw: my_error 2> error(bad_arg). ** exception error: bad_arg 3> exit(reason). ** exception exit: reason

A division by zero, 1/0, and a pattern that does not fit, {ok, X} = {error, missing}, are raised by the runtime as error with the reason badarith and {badmatch, {error, missing}}. The programmer writes none of those calls. That is why a crash in Erlang is not a special case a program has to prepare for: a bad value simply fails the function that met it.

try, catch and the stacktrace

try evaluates a body and names the classes it handles. A catch clause may bind only the reason, or the reason and the stacktrace. The stacktrace is the list of calls that led to the failure, and it is the only cheap way to log where a caught error came from. This module runs four funs and labels what each one did:

classify.erl

-module(classify). -export([main/0]). describe(Fun) -> try Fun() of Value -> {returned, Value} catch throw:Term -> {thrown, Term}; error:Reason:Stacktrace -> {failed, Reason, Stacktrace =/= []}; exit:Reason -> {exited, Reason} end. main() -> io:format("~p~n", [describe(fun() -> 42 end)]), io:format("~p~n", [describe(fun() -> throw(no_permission) end)]), io:format("~p~n", [describe(fun() -> error(badarg) end)]), io:format("~p~n", [describe(fun() -> exit(shutdown) end)]).

erlc classify.erl

erl -noshell -eval 'classify:main(), halt().'

{returned,42} {thrown,no_permission} {failed,badarg,true} {exited,shutdown}

Two details are easy to miss. The of part is optional and runs only when the body returned normally, so a value is never confused with an exception. The stacktrace clause has three patterns, Class:Reason:Stacktrace, and drops the trace when it only writes Class:Reason. The old erlang:get_stacktrace/0 was removed in OTP 21; a handler that still calls it does not compile.

Recovering from a bad value

The usual place for try is the edge of a program that reads untrusted input. binary_to_integer/1 raises badarg on anything that is not a number, and the handler turns that into the {error, Reason} value the rest of the program already knows. A guard in the of branch rejects a number that parsed but is out of range:

parse_port.erl

-module(parse_port). -export([main/0, port/1]). port(Text) -> try binary_to_integer(Text) of Number when Number >= 1, Number =< 65535 -> {ok, Number}; _Number -> {error, out_of_range} catch error:badarg -> {error, not_a_number} end. main() -> io:format("~p~n", [port(<<"8080">>)]), io:format("~p~n", [port(<<"eighty">>)]), io:format("~p~n", [port(<<"70000">>)]).

erlc parse_port.erl

erl -noshell -eval 'parse_port:main(), halt().'

{ok,8080} {error,not_a_number} {error,out_of_range}

Notice that the function returns the same shape for every failure. The caller does not need to know whether the number was unreadable or too large unless the reason matters to it, and an unreadable string no longer crashes the process that handles the request. The type conversions lesson covers the other direction, from a value to text.

The after clause

after runs whether the body returned, raised or threw, and it cannot replace the result. That is exactly the shape of a resource: open it, use it, release it, and release it even when the use fails. The module below prints the two edges of the resource around a fun, once with a fun that returns and once with a fun that raises:

resource.erl

-module(resource). -export([main/0]). use(Fun) -> try io:format("open~n"), Fun() after io:format("close~n") end. main() -> io:format("~p~n", [use(fun() -> 7 end)]), try use(fun() -> error(zero) end) catch error:zero -> caught end, io:format("done~n").

erlc resource.erl

erl -noshell -eval 'resource:main(), halt().'

open close 7 open close done

The second open is followed by close even though error(zero) replaced the result of the body, and the outer try turns that error into the atom caught, so done still prints. In real code the cleanup is a file:close/1, a gen_tcp:close/1 or an ets:delete/1. The files lesson uses the same shape around a file handle.

The catch that hides a bug

A catch clause of _:_ matches every class and every reason, so it also catches the mistakes the programmer did not think of. This module counts a list, and a catch-all turns a value that is not a list into the number zero:

swallow.erl

-module(swallow). -export([main/0]). count(Items) -> try length(Items) catch _:_ -> 0 end. main() -> io:format("~p~n", [count([a, b, c])]), io:format("~p~n", [count(not_a_list)]).

erlc swallow.erl

erl -noshell -eval 'swallow:main(), halt().'

3 0

The program prints 0 for a value that is not a list at all, and the caller cannot tell an empty list from a bug. The failure has been moved from the line that caused it to a wrong number much later, which is the hardest kind of bug to find. The honest version catches only the class it can repair, as parse_port catches badarg, and lets everything else crash the process. A supervisor restarts the process, and the crash report keeps the stacktrace; the let it crash lesson explains why that is the normal design.

The other mistake is to catch exit in a process that is shutting down: the exit signal of a supervisor is not a failure to repair, and a handler that turns it into {error, shutdown} keeps a process alive that the system has already decided to stop.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which three classes of exception does Erlang have?

    Answer

    throw, error, exit

    throw carries a value, error carries an error term, and exit carries a reason between processes.

  2. What does throw(my_error). print in the shell?

    Answer

    ** exception throw: my_error

    An uncaught throw is reported with its class and the value it carries.

  3. Which clause handles a throw in try F() catch error:Why -> ...; throw:What -> ... end.?

    Answer

    The throw clause

    A catch clause names its class, so a throw reaches the throw line.

  4. When does an after clause run?

    Answer

    Whether the body succeeds, fails, or throws

    after always runs, which is what makes it useful for releasing a handle.

  5. What does this module print? -module(q1). -export([main/0]). main() -> Result = try throw(stop) catch error:_ -> wrong; throw:Reason -> {thrown, Reason} end, io:format("~p~n", [Result]).

    Answer

    {thrown,stop}

    The throw matches the throw clause, which keeps the reason in a tuple.

  6. What does this module print? -module(q2). -export([main/0]). text() -> <<"12x">>. main() -> R = try binary_to_integer(text()) catch error:badarg -> {error, badarg} end, io:format("~p~n", [R]).

    Answer

    {error,badarg}

    binary_to_integer/1 raises badarg, and the catch clause returns its own tuple for that reason.

  7. What does this module print? -module(q3). -export([main/0]). main() -> R = try throw(stop) catch throw:Reason -> {thrown, Reason} after io:format("cleanup~n") end, io:format("~p~n", [R]).

    Answer

    cleanup / {thrown,stop}

    The after body runs before the catch returns its value, so cleanup comes first.

  8. What does this module print? -module(q4). -export([main/0]). count(Items) -> try length(Items) catch _:_ -> 0 end. main() -> io:format("~p~n", [count(not_a_list)]).

    Answer

    0

    The catch-all turns the failure into zero, which is exactly the bug this lesson warns about.

  9. Why is a catch-all clause _:_ -> ok dangerous?

    Answer

    It hides bugs the programmer did not expect

    It also catches mistakes the code was never meant to handle, and the failure surfaces later as a wrong value.

  10. What should a try normally catch?

    Answer

    Only the classes the code can actually repair

    A handler that repairs only what it understands lets every other failure crash the process and be reported.

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.

Автор статьи: Arthur Isaev