TExcelTAD
Home › Elixir › Elixir try, catch, rescue & Error Tuples

Elixir try, catch, rescue & Error Tuples

Elixir distinguishes between expected failures, which are part of normal program flow, and unexpected ones, which are bugs or broken environments. The idiom is simple:

  • Expected failures (a missing file, invalid input, a user not found) return {:error, reason} tuples, and callers handle them with case or with.
  • Unexpected failures raise exceptions, and usually nobody rescues them: the process crashes and its supervisor restarts it.

Error tuples

elixir · try it yourself
defmodule Account do
  def parse_amount(text) do
    case Float.parse(text) do
      {amount, ""} when amount > 0 -> {:ok, amount}
      {_amount, ""} -> {:error, :not_positive}
      _ -> {:error, :invalid_format}
    end
  end
end

for input <- ["12.50", "-3", "ten"] do
  case Account.parse_amount(input) do
    {:ok, amount} -> IO.puts("#{input}: accepted #{amount}")
    {:error, reason} -> IO.puts("#{input}: rejected (#{reason})")
  end
end
12.50: accepted 12.5
-3: rejected (not_positive)
ten: rejected (invalid_format)

Many standard library functions come in pairs: File.read/1 returns a tuple, File.read!/1 returns the value or raises. Write your own functions the same way when callers may want either style.

raise and rescue

raise "message" raises a RuntimeError; raise SomeError, opts raises a specific exception. try/rescue catches exceptions, optionally by type:

elixir · try it yourself
risky = fn
  :runtime -> raise "something went wrong"
  :argument -> raise ArgumentError, "expected a positive number"
  :arith -> 1 / Enum.count([])
  :key -> Map.fetch!(%{}, :name)
  :ok -> :all_good
end

for kind <- [:runtime, :argument, :arith, :key, :ok] do
  result =
    try do
      risky.(kind)
    rescue
      e in [ArgumentError, KeyError] -> "input problem: " <> Exception.message(e)
      e in ArithmeticError -> "math problem: " <> Exception.message(e)
      e -> "other #{inspect(e.__struct__)}: " <> Exception.message(e)
    end

  IO.puts("#{kind} -> #{result}")
end
runtime -> other RuntimeError: something went wrong
argument -> input problem: expected a positive number
arith -> math problem: bad argument in arithmetic expression
key -> input problem: key :name not found in:

    %{}

ok -> all_good

Exception.message/1 returns the text of any exception. The last clause e -> rescues every exception.

else, after

try can also have an else block (runs when nothing was raised, receives the result) and an after block (always runs, like finally in other languages):

elixir · try it yourself
read_config = fn path ->
  try do
    File.read!(path)
  rescue
    File.Error -> {:error, :unreadable}
  else
    contents -> {:ok, String.length(contents)}
  after
    IO.puts("(checked #{path})")
  end
end

File.write!("/tmp/app.conf", "debug=true\n")
IO.inspect(read_config.("/tmp/app.conf"))
IO.inspect(read_config.("/tmp/none.conf"))
(checked /tmp/app.conf)
{:ok, 11}
(checked /tmp/none.conf)
{:error, :unreadable}

Custom exceptions

defexception defines an exception struct. Provide default fields and, if useful, a message/1 function:

elixir · try it yourself
defmodule InsufficientStock do
  defexception [:item, :wanted, :available]

  @impl true
  def message(e), do: "only #{e.available} #{e.item} left, #{e.wanted} requested"
end

defmodule Warehouse do
  def take!(item, wanted, available) when wanted > available do
    raise InsufficientStock, item: item, wanted: wanted, available: available
  end

  def take!(_item, wanted, available), do: available - wanted
end

IO.inspect(Warehouse.take!("chairs", 2, 10))

try do
  Warehouse.take!("chairs", 12, 10)
rescue
  e in InsufficientStock -> IO.puts("#{Exception.message(e)} (wanted: #{e.wanted})")
end
8
only 10 chairs left, 12 requested (wanted: 12)

By convention, functions that raise end with !.

throw/catch and exit

Besides exceptions there are two other kinds of non-local exits, both caught with catch kind, value:

Kind Started with Typical use
:error raise (exceptions) errors; rescue is the usual way to catch them
:throw throw(value) rare: escaping early from deep code you don't control
:exit exit(reason), a failed GenServer.call process termination signals
elixir · try it yourself
first_big =
  try do
    Enum.each([3, 8, 12, 40, 7], fn n -> if n > 10, do: throw({:found, n}) end)
    :none
  catch
    :throw, {:found, n} -> n
  end

IO.inspect(first_big)

result =
  try do
    exit(:shutdown_requested)
  catch
    :exit, reason -> "caught exit: #{inspect(reason)}"
  end

IO.puts(result)
12
caught exit: :shutdown_requested

In idiomatic code throw is almost never needed: Enum.find(list, &(&1 > 10)) does the same as the example above. It is shown so you can recognise it.

What happens without rescue

An uncaught exception stops the process and prints the error with a stack trace. In a script that ends the program:

text
** (RuntimeError) something went wrong
    main.exs:3: (file)

In an application, the crash is logged and the supervisor restarts the process. That is often the right outcome: rescuing an exception you can't really handle just hides the bug.

Guidelines

  • Return {:ok, value} / {:error, reason} for failures the caller should handle.
  • Offer a ! variant that raises, for callers who consider failure a bug.
  • Rescue only exceptions you can do something useful about, and as close as possible to where they happen.
  • Don't use exceptions for control flow; use pattern matching.

Test yourself

Which is the idiomatic way to report "user not found" from a function?

  1. raise "not found"
  2. Return {:error, :not_found}
  3. Return nil and log
  4. throw(:not_found)

When does the after block of a try run?

  1. Only if an exception was raised
  2. Only if nothing was raised
  3. Always
  4. Never in scripts

How do you catch exit(:boom)?

  1. rescue e -> ...
  2. catch :exit, reason -> ...
  3. catch :throw, reason -> ...
  4. It cannot be caught