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 withcaseorwith. - Unexpected failures raise exceptions, and usually nobody rescues them: the process crashes and its supervisor restarts it.
Error tuples
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
end12.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:
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}")
endruntime -> 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):
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:
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})")
end8
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 |
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:
** (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?
raise "not found"- Return
{:error, :not_found} - Return
niland log throw(:not_found)
When does the after block of a try run?
- Only if an exception was raised
- Only if nothing was raised
- Always
- Never in scripts
How do you catch exit(:boom)?
rescue e -> ...catch :exit, reason -> ...catch :throw, reason -> ...- It cannot be caught