Let it crash: error handling

Three ways to fail

An Erlang process fails with a class and a reason. throw carries any value and is the explicit signal of a computation that cannot continue, error marks a programming fault such as a bad argument or a failed match, and exit asks the process to die. The shell prints all three the same way, with the class first.

erl

1> throw(my_error).
** exception throw: my_error
2> error(badarg).
** exception error: bad argument
3> exit(normal).
** exception exit: normal

The runtime raises the same errors itself. A failed match is an error with the value as its reason, an arithmetic fault is an error with a sentence for a reason, and a function called with no matching clause is an error with the function and its arguments. None of them needs a try to happen: the process simply stops, and the shell prints the report and starts the next line.

catch and try

catch turns any exception into a value. It is fast to write and it loses the stack trace and the class, which is why production code uses try instead. try names the class and the reason, and try with no catch clause is a plain assertion on the happy path. Save this module as safe.erl.

-module(safe). -export([divide/2, read/1, parse/1]). divide(_A, 0) -> exit(divide_by_zero); divide(A, B) -> A / B. read(Path) -> try file:read_file(Path) of {ok, Bin} -> {ok, byte_size(Bin)}; {error, Reason} -> {error, Reason} after io:format("read finished~n") end. parse(Text) -> try list_to_integer(Text) catch error:badarg -> {error, not_a_number} end.

erlc safe.erl
erl

1> catch throw(my_error).
my_error
2> safe:parse("42").
42
3> safe:parse("forty").
{error,not_a_number}
4> try safe:divide(10, 2) catch exit:Reason -> {exit, Reason} end.
5.0
5> try safe:divide(10, 0) catch exit:Reason -> {exit, Reason} end.
{exit,divide_by_zero}

Catch only what you can handle. parse/1 turns one known error into a value the caller can act on, and that is a good catch. A catch that turns every error into {error, unknown} hides the bug that caused it, and the caller retries forever.

after always runs

The after block runs whether the body returned or raised, which makes it the place for the cleanup: closing a file, releasing a lock, sending a message. read/1 shows the shape with an io:format in place of a real close.

erl

1> safe:read("missing.txt").
read finished
{error,enoent}

A file that does not exist is not an exception here: file:read_file answers an error tuple, the of clause turns it into a value, and after prints its line on the way out. Had the body raised, after would still have printed the line, and the exception would have continued to the caller.

Let the supervisor restart

Let it crash is not advice to write broken code. It says that a process which cannot recover should die quickly, with a full crash report, and that a supervisor should start a fresh one with a clean state. That is cheaper and safer than a rescue that keeps a half broken state alive.

The rules that follow: validate input at the edge and reject it there, keep the crash inside one process so the rest of the system keeps running, and let the supervisor strategy of lesson 35 decide whether one child or a whole group restarts. For the rare case of a shared resource, put it in a gen_server and let the server own it: then one crash cannot leave the resource locked.

Next: ETS tables

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 and exit

    Every exception is a throw, an error or an exit, and try names the class in each clause.

  2. What does throw(Value) do?

    Answer

    Raises an exception of class throw with that value

    A throw is the explicit signal that a computation cannot produce an answer.

  3. What does the shell print for error(badarg)?

    Answer

    ** exception error: bad argument

    The class is error and the standard reason for badarg reads as bad argument.

  4. What does exit(normal) mean to a linked process?

    Answer

    It is a normal exit and is not a crash

    The reason normal marks a clean exit; supervisors do not treat it as a crash.

  5. What does the catch expression lose compared with try?

    Answer

    The class and the stack trace

    catch answers the value or a bare exit tuple, so the class and the trace are gone.

  6. What does try ... of ... catch ... end name in each clause?

    Answer

    The class and the reason

    A clause looks like error:Reason ->, so the class decides which clause runs.

  7. When does the after block run?

    Answer

    Always, on both paths

    after is the cleanup path, so it runs whichever way the body left.

  8. What does file:read_file/1 answer for a missing file?

    Answer

    {error, enoent}

    A missing file is a normal error tuple, so the of clause can turn it into a value.

  9. 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.

  10. Which catch is considered good?

    Answer

    One that handles a specific 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.

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