try, rescue, catch and after

A try block in Elixir has up to four parts: rescue for an exception, catch for a throw, an else for the value of the body when nothing failed, and after for the code that must run either way. Each part is optional, and a block that has one clause is a block that says what it handles and lets the rest through.

try, rescue and after

The body runs first; the exception it raises is caught by the rescue clause, and the after block runs whatever happened. The program below prints a line before the failure, a line from the clause and a line from the block that always runs:

tryrescue.exs

try do IO.puts("work") raise "boom" rescue e in RuntimeError -> IO.puts("rescued: #{e.message}") after IO.puts("cleanup") end

elixir tryrescue.exs

work
rescued: boom
cleanup

The value of the whole try is the value of the body, or of the clause that ran. after has no value of its own, which is why it is the place for closing a file or releasing a lock: code that has an effect rather than an answer.

The part that always runs

after runs before the exception leaves the block, so a crash inside the body still finds the resource released. The second block below raises with no rescue at all, and the program ends with the exception after the cleanup line:

after.exs

try do IO.puts("open") after IO.puts("close") end try do raise "fail" after IO.puts("closed after the crash") end

elixir after.exs

open
close
closed after the crash
** (RuntimeError) fail
    after.exs:8: (file)
    (elixir 1.19.7) lib/code.ex:1613: Code.require_file/2

The first block has no rescue and no exception, and its after still runs. The output order is the point: the cleanup line is printed before the report of the crash, so a reader can see that the release happened while the program was already failing. A function that opens a file writes the close in after for the same reason, or uses a function that does it, as the files lesson shows.

catch, for a throw

throw/1 is not an exception: it is a value sent to the nearest catch, and the code that reads it is a catch clause. The two are separate mechanisms, and the clause below catches the atom the body threw:

catch.exs

try do throw(:halt) catch :halt -> IO.puts("caught the throw") end

elixir catch.exs

caught the throw

A throw is the cheap non-local exit of Erlang, and a library uses it for a control flow that is not an error; a program of Elixir rarely throws and rarely catches. The clause may name the kind, :error, :exit or :throw, and a catch with no pattern catches all three, which is broader than most programs need.

When rescue is the wrong tool

A failure the program expects is a value, not an exception: a missing file, a bad number and a refused connection are all answers of the ok and error tuple kind. Rescuing them hides the branch that should handle them:

expected.exs

result = File.read("missing.txt") case result do {:ok, text} -> IO.puts(text) {:error, reason} -> IO.puts("no file: #{reason}") end

elixir expected.exs

no file: enoent

This is the shape a program wants for everything it can foresee: no exception, no stack, one branch per answer and a report that names the reason. A rescue is for the failure the program did not foresee, at the edge where it talks to the world: a library that raises, a message in a shape the code did not expect, a bug in a dependency. Catching those at the top and turning them into a logged error is the last line of a program, not its control flow.

The mistake: rescue does not catch a throw

A reader who has met rescue expects it to catch everything the body stops with. It catches exceptions only, so a throw goes past it and leaves the block:

mistake.exs

try do throw(:halt) rescue e -> IO.puts("rescued #{inspect(e)}") end

elixir mistake.exs

** (throw) :halt
    mistake.exs:2: (file)
    (elixir 1.19.7) lib/code.ex:1613: Code.require_file/2

The report says ** (throw) :halt rather than an exception name, which is the sign that the value came from throw/1. The clause to add is catch :halt -> ... in the same try, and a program that writes it has decided to speak the language of the code it calls. The other two kinds a catch sees are :exit from a dying process and :error from a raise.

The programs on this page were run with Elixir 1.19.7 on Erlang/OTP 27 (erts 15.2.7.14), on Linux x86_64 in a Docker container.

Questions

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

  1. Which part of a try block runs whether the body fails or not?

    Answer

    after

    after is the block that always runs, which is where a resource is released.

  2. What does a catch clause catch?

    Answer

    a throw, an exit or an error, by the kind the clause names

    catch handles the three kinds of non-local exit, and a clause may name one of them.

  3. When is rescue the wrong tool?

    Answer

    when the failure is expected and has an ok or error tuple

    An expected failure is a value the caller branches on; a rescue hides that branch.

  4. What does throw/1 do?

    Answer

    sends the value to the nearest catch clause

    A throw is a non-local exit of its own, caught by catch and not by rescue.

  5. What does this program print? try do IO.puts("a") raise "x" rescue _ -> IO.puts("b") after IO.puts("c") end

    Answer

    a / b / c

    The body prints a, the clause prints b, and after prints c.

  6. What does this program print? try do throw(:stop) catch :stop -> IO.puts("caught") end

    Answer

    caught

    The catch clause names the thrown atom and prints its line.

  7. What does this program print? try do IO.puts("open") after IO.puts("close") end

    Answer

    open / close

    The body runs and the after block runs too, even with no exception.

  8. What does this program do? try do raise "fail" after IO.puts("cleanup") end

    Answer

    cleanup

    after runs before the exception continues, so the cleanup line is the output the program prints.

  9. What does this program print? case File.read("missing.txt") do {:ok, text} -> IO.puts(text) {:error, reason} -> IO.puts("error #{reason}") end

    Answer

    error enoent

    The call answers the error tuple and the second clause prints the reason.

  10. What does this program do? try do throw(:halt) rescue e -> IO.puts("rescued") end

    Answer

    A throw, because rescue does not catch a throw

    rescue handles exceptions, so the throw goes past it and ends the program.

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