Let it crash: error handling
An Erlang process has two ways to end a call: it answers, or it dies. There is no third one, and the runtime makes the second cheap: the failure stays in the process that raised it, the process that linked to it gets a report, and a supervisor starts a fresh one. The exceptions lesson shows the syntax of try and catch; this one is about the decision behind it, which is the half of error handling that the syntax does not make for you.
Three classes of failure
Every exception carries a class and a reason. throw(Value) is the explicit signal that the computation cannot produce an answer here, and its reason is whatever value the caller needs. error(Reason) marks a programming fault, such as a bad argument or a failed match. exit(Reason) asks the current process to stop. The program catches all three and prints the class with the reason, because try ... catch Class:Reason is the only form that keeps both:
failure.erl
-module(failure). -export([main/0]). main() -> io:format("throw: ~p~n", [caught(fun() -> throw(my_error) end)]), io:format("error: ~p~n", [caught(fun() -> error(badarg) end)]), io:format("exit: ~p~n", [caught(fun() -> exit(normal) end)]). caught(Fun) -> try Fun() catch Class:Reason -> {Class, Reason} end.
erlc failure.erl
erl -noshell -eval 'failure:main(), halt().'
throw: {throw,my_error} error: {error,badarg} exit: {exit,normal}
The atom printed as the reason of the error is badarg, while the shell translates it to a sentence. That is a property of the shell, not of the exception: a catcher compares and stores the atom, and the sentence exists for the reader. exit(normal) is a clean stop, and a supervisor does not restart a child that ended with it; any other reason is a crash.
What the runtime raises
Most exceptions are raised by the runtime, not by a call to error/1. The reason of such an error is an atom the runtime chooses: badarith for an arithmetic expression that has no value, badarg for an argument of the wrong type, badmatch for a failed match, function_clause for a call that no clause accepts and case_clause for a case whose clauses all refuse the value. The program below reads two values from a file, so that the compiler cannot see them and reject the calls before the run, and catches the two faults:
reasons.erl
-module(reasons). -export([main/0]). main() -> ok = file:write_file("input.txt", <<"0 10x">>), {ok, Bin} = file:read_file("input.txt"), [Zero, Text] = binary:split(Bin, <<" ">>, [global]), io:format("badarith: ~p~n", [caught(fun() -> 1 / binary_to_integer(Zero) end)]), io:format("badarg: ~p~n", [caught(fun() -> binary_to_integer(Text) end)]), ok = file:delete("input.txt"). caught(Fun) -> try Fun() catch Class:Reason -> {Class, Reason} end.
erlc reasons.erl
erl -noshell -eval 'reasons:main(), halt().'
badarith: {error,badarith} badarg: {error,badarg}
The reason of a failed match is the whole tuple {badmatch, Value}, so a catcher can see what arrived instead of what was expected, while a function_clause or a case_clause carries no value at all. The shell prints each class as a sentence with the stack trace below it, which is where the words bad argument and no match of right hand side value come from. This is why Erlang code checks the shape of its data with pattern matching instead of with tests: the match is the check, and a wrong shape stops exactly here, with the value in the report.
after always runs
try ... after runs the after block whether the body answered or raised, which makes it the place for the cleanup: closing a file, releasing a lock, sending a reply. The program below prints the cleanup line from both paths and shows the order: the block runs before the value of the try leaves it.
cleanup.erl
-module(cleanup). -export([main/0]). main() -> io:format("ok path: ~p~n", [attempt(fun() -> {ok, 42} end)]), io:format("crash path: ~p~n", [attempt(fun() -> error(broken) end)]). attempt(Fun) -> try Fun() of Value -> {value, Value} catch error:Reason -> {failed, Reason} after io:format("cleanup ran~n") end.
erlc cleanup.erl
erl -noshell -eval 'cleanup:main(), halt().'
cleanup ran ok path: {value,{ok,42}} cleanup ran crash path: {failed,broken}
The crash path caught the error, so the program continued; if the catch clause were removed, the cleanup would still run and the exception would continue to the caller after it. Use after for what must happen in both cases, and never put the reply of a protocol there: a caller that already got an error tuple does not expect a second answer.
Catch what you can act on
A catch clause that matches one class and one reason is a decision: the program knows what went wrong and has an answer. The parser below accepts a port number, rejects a number outside the range and turns the one error list_to_integer/1 raises into a value. Everything else is left to the caller.
parse.erl
-module(parse). -export([main/0]). main() -> io:format("~p~n", [port("8080")]), io:format("~p~n", [port("eighty")]), io:format("~p~n", [port("-1")]). port(Text) -> try list_to_integer(Text) of Number when Number > 0, Number < 65536 -> {ok, Number}; Number -> {error, {out_of_range, Number}} catch error:badarg -> {error, not_a_number} end.
erlc parse.erl
erl -noshell -eval 'parse:main(), halt().'
{ok,8080} {error,not_a_number} {error,{out_of_range,-1}}
The range is checked in the of clauses with a guard, not in a catch: a number that parses but does not fit is a value the caller can report, not an exception. The catch expression, written without try, does the opposite and hides the class: catch throw(my_error) answers my_error, while catch error(badarg) answers an 'EXIT' tuple whose second element is the reason and whose tail is the stack. A processor that catches every class with _:_ and answers {error, unknown} loses the bug that caused it, and the caller retries forever.
Let the supervisor restart
Let it crash is not advice to write broken code. It says that a process which cannot recover should die at once, with a crash report, and that a supervisor should start a new one with a clean state. That is cheaper and safer than a rescue that keeps a half broken state alive. The program below is a supervisor and its worker in one module: two bumps raise the counter to two, the worker is killed, and the supervisor starts another one whose counter is zero.
restart.erl
-module(restart). -behaviour(supervisor). -export([main/0, bump/0, value/0, start_worker/0]). -export([init/1]). main() -> logger:set_primary_config(level, none), {ok, _Sup} = supervisor:start_link({local, ?MODULE}, ?MODULE, []), bump(), bump(), io:format("before the crash: ~p~n", [value()]), Old = whereis(worker), exit(Old, boom), _New = wait_for_new_worker(Old, 200), io:format("after the restart: ~p~n", [value()]). bump() -> worker ! {bump, self()}, receive {count, Count} -> Count end. value() -> worker ! {value, self()}, receive {count, Count} -> Count end. wait_for_new_worker(_Old, 0) -> exit(no_worker); wait_for_new_worker(Old, Tries) -> case whereis(worker) of Pid when is_pid(Pid), Pid =/= Old -> Pid; _Other -> timer:sleep(10), wait_for_new_worker(Old, Tries - 1) end. start_worker() -> Pid = spawn_link(fun() -> true = register(worker, self()), loop(0) end), {ok, Pid}. init([]) -> SupFlags = #{strategy => one_for_one, intensity => 5, period => 10}, Child = #{id => worker, start => {?MODULE, start_worker, []}, restart => permanent, shutdown => 5000, type => worker, modules => [?MODULE]}, {ok, {SupFlags, [Child]}}. loop(Count) -> receive {bump, From} -> From ! {count, Count + 1}, loop(Count + 1); {value, From} -> From ! {count, Count}, loop(Count) end.
erlc restart.erl
erl -noshell -eval 'restart:main(), halt().'
before the crash: 2 after the restart: 0
The worker is not a gen_server, because the point here is the restart and not the protocol: any process with a start function that answers {ok, Pid} is a supervisor child. Three rules follow from the example. Validate input at the edge and reject it there, so a bad value never reaches the worker. Keep the crash inside one process, so the rest of the system keeps running. Let the strategy of the tree decide whether one child or a whole group restarts; a one_for_one tree costs one process, and the plan of a nested tree is the supervision trees lesson.
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,errorandexitEvery exception is a throw, an error or an exit, and
trynames the class in each clause. -
What does the reason of a failed match carry?
Answer
{badmatch, Value}, the value that arrivedThe runtime puts the value that did not match into the reason, so the catcher can report it.
-
When does the
afterblock of atryrun?Answer
Always, on both paths
afteris the cleanup path, so it runs whichever way the body left thetry. -
What does the
catchexpression lose compared withtry?Answer
The class and the stack trace
catchanswers the value or a bare'EXIT'tuple, so the class is gone and the trace is inside the tuple. -
What does let it crash mean in practice?
Answer
Let a process die and let its supervisor restart it
A quick death with a clear report beats a process that keeps running with broken state.
-
Which catch is the useful one?
Answer
One that handles a known error and lets the rest through
Handling the error you can act on is useful; hiding the ones you cannot is how bugs survive.
-
What does this module print?
-module(q1). -export([main/0]). main() -> R = try throw(stop) catch Class:Reason -> {Class, Reason} end, io:format("~p~n", [R]).Answer
{throw,stop}The
catchclause binds the classthrowand the reasonstopand builds the tuple. -
What does this module print?
-module(q2). -export([main/0]). main() -> io:format("~p~n", [run()]). run() -> try 1 + 2 of N -> io:format("body~n"), N * 2 after io:format("cleanup~n") end.Answer
body/cleanup/6The body prints first,
afterruns before the value leaves thetry, and the caller prints the result last. -
What does this module print?
-module(q3). -export([main/0]). main() -> io:format("~p~n", [check("70000")]). check(Text) -> try list_to_integer(Text) of N when N < 65536 -> {ok, N}; N -> {too_big, N} catch error:badarg -> not_a_number end.Answer
{too_big,70000}The text parses, so the
ofclauses decide, and the guard sends the value to the second clause. -
What does this module print?
-module(q4). -export([main/0]). main() -> R = try exit(shutdown) catch Class:Reason -> {Class, Reason} end, io:format("~p~n", [R]).Answer
{exit,shutdown}A
tryinside the same process catches its own exit, and the clause keeps the class and the reason.
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