Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 48 ยท Protocols, Errors and Tooling

Error Handling: Tuples, with and Exceptions

Learn how Elixir handles errors with {:ok, value} and {:error, reason} tuples, the with expression, raise and rescue, try/catch, custom exceptions and let it crash.

Things go wrong: files are missing, input is malformed, a network call times out. Elixir has two separate mechanisms for this, and learning which to use is most of the skill. For expected failures, the kind a caller can reasonably handle, functions return a tagged tuple such as {:error, :not_found}. For unexpected failures, the kind that mean a bug or a broken assumption, code raises an exception, and a supervisor restarts the broken part. This second idea has a famous name: let it crash.

You already know pattern matching and conditionals. Here you will use them to handle results, chain steps with with, raise and rescue exceptions, define your own, and decide when not to handle an error at all.

Elixir is not installed on this site, so the Elixir code is read-only. The runnable examples are JavaScript stand-ins for the ideas (result objects, a with-like chain, try/catch). They are not Elixir and do not model every rule.

Tagged tuples: the {:ok, value} convention

By convention a function that can fail returns {:ok, value} on success and {:error, reason} on failure. Many standard functions follow this:

ELIXIR
File.read("notes.txt")        # {:ok, "contents..."} or {:error, :enoent}
Integer.parse("42abc")        # {42, "abc"}  (a variation: :error when nothing parses)
Map.fetch(%{a: 1}, :a)        # {:ok, 1}
Map.fetch(%{a: 1}, :b)        # :error

The caller decides what to do by matching:

ELIXIR
case File.read("notes.txt") do
  {:ok, text} -> String.length(text)
  {:error, :enoent} -> 0
  {:error, reason} -> raise "could not read: #{inspect(reason)}"
end

The reason is usually an atom (:enoent, :timeout, :invalid_email) or a small map. Atoms are easy to match on and cheap to compare. A success value can be any term, so the tag is what tells the cases apart.

The bang convention

Many modules offer two versions of a function. The plain one returns a tuple. The one ending in ! returns the bare value and raises on failure:

ELIXIR
File.read("notes.txt")     # {:ok, binary} | {:error, reason}
File.read!("notes.txt")    # binary, or raises File.Error
Map.fetch!(%{a: 1}, :b)    # raises KeyError

Use the plain function when failure is a normal outcome you will handle. Use the bang version when failure would mean a bug (a config file that must exist) and crashing is the right response. When you write your own APIs, follow the same pattern.

Two kinds of failure

Expected The caller can handle it. Return {:error, reason}.
Unexpected A bug or broken assumption. Raise, and let it crash.

Do not wrap everything in rescue. Most errors need no handler.

1 / 2

Chaining steps with with

Real work has several steps, each of which can fail. Nested case expressions pile up quickly:

ELIXIR
case parse_age(params) do
  {:ok, age} ->
    case check_adult(age) do
      {:ok, age} -> register(age)
      {:error, _} = error -> error
    end

  {:error, _} = error ->
    error
end

The with expression flattens this. Each line of the form pattern <- expression runs the expression and tries to match. If every match succeeds, the do block runs. At the first mismatch, with stops and returns the value that failed to match:

ELIXIR
with {:ok, age} <- parse_age(params),
     {:ok, age} <- check_adult(age),
     {:ok, user} <- register(age) do
  {:ok, user}
end
# on failure, returns the first {:error, reason} that did not match

Add an else block to translate failures. It matches the non-matching value like a case:

ELIXIR
with {:ok, age} <- parse_age(params),
     true <- age >= 18 do
  :welcome
else
  :error -> {:error, :not_a_number}
  false -> {:error, :too_young}
end

Plain expressions (without <-) can sit between steps, for example name = String.trim(name). Keep else clauses small. If you need many of them, the steps probably return incompatible error shapes, and it is cleaner to normalize those inside the helper functions.

JS A with-like chain, JavaScript stand-in

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Exceptions: raise and rescue

An exception is a struct that says what went wrong. Raise one with raise/1 and a message, or raise/2 with a module and fields:

ELIXIR
raise "something broke"                       # RuntimeError
raise ArgumentError, message: "bad input"     # ArgumentError
raise ArgumentError, "bad input"              # same, shorter

Catch it with try and rescue:

ELIXIR
try do
  String.to_integer("abc")
rescue
  e in ArgumentError -> {:error, Exception.message(e)}
end

You can rescue several types, bind the exception, or rescue everything with a bare variable:

ELIXIR
try do
  risky()
rescue
  e in [ArgumentError, KeyError] -> handle(e)
  e -> reraise e, __STACKTRACE__
after
  cleanup()
end

after always runs, even if the block raised, which makes it the place for closing resources. reraise/2 rethrows with the original stack trace. Unrecognized errors you cannot deal with should usually be re-raised or simply not rescued.

Common built-in exceptions include ArgumentError, ArithmeticError (for 1 / 0), KeyError, MatchError, FunctionClauseError, CaseClauseError, RuntimeError and File.Error.

Defining your own exception

Use defexception inside a module. The module becomes the exception type:

ELIXIR
defmodule InsufficientFunds do
  defexception [:balance, :needed]

  @impl true
  def message(%{balance: balance, needed: needed}) do
    "balance #{balance} is below the #{needed} needed"
  end
end

raise InsufficientFunds, balance: 10, needed: 25

Name exceptions after what went wrong, and put the useful facts in fields so handlers do not have to parse a message.

throw, exit and catch

Elixir has two other non-local exits. throw/1 and catch are meant for early return from deep code, and are rarely needed. exit/1 signals that the current process should stop, which supervisors and links react to (later in the course). Both are caught with catch:

ELIXIR
try do
  throw(:found)
catch
  :throw, value -> {:caught, value}
end

try do
  exit(:shutdown)
catch
  :exit, reason -> {:exit, reason}
end

If you find yourself reaching for throw, first try returning a tuple, using Enum.find/2 or restructuring with recursion. Real code uses catch mostly at boundaries, for example to protect a worker loop from a failing callback.

JS try, catch and finally in JavaScript

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Let it crash

Elixir programmers do not guard every line with rescue. Code that tries to handle every possible failure becomes long and hides the real logic, and it still misses the failures nobody imagined. Instead, processes are cheap, isolated and supervised. When a process hits an unexpected state, it crashes, its supervisor starts a fresh copy in a known-good state, and nothing else is affected.

flowchart LR
  A["Worker process"] -->|"unexpected error"| B["Crash"]
  B --> C["Supervisor notices"]
  C -->|"restart"| D["Fresh worker, clean state"]

A crash is contained and repaired by a supervisor instead of being handled inline.

That gives a practical rule of thumb:

  • Validate input at the boundary (user input, files, network) and return {:error, reason}.
  • Do not defend against your own bugs with rescue. Let a pattern match fail (MatchError) or a function clause error surface, so the problem is visible.
  • Rescue only when you can do something useful: translate the error, retry, clean up or log and continue.

Processes and supervision come in the concurrency chapter. For now, remember that not handling an error is a deliberate design choice, not carelessness.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the convention for a function that can fail in an expected way?

    Tagged tuples let the caller match on the outcome and carry a reason. nil and booleans lose the reason.
  2. 2. What does with return when one of its <- clauses does not match?

    with stops at the first mismatch and returns that value as it is. An else block can match and translate it.
  3. 3. What is the usual difference between File.read/1 and File.read!/1?

    The bang version unwraps the success value and raises on failure, so use it when failure would mean a bug.
  4. 4. When does the after block of try always run?

    after is for cleanup and runs in every case, like finally in other languages.

Summary

  • Return {:ok, value} or {:error, reason} for expected failures; match on them with case or with.
  • A trailing ! means "return the value or raise".
  • with flattens a chain of fallible steps and returns the first non-matching value, optionally translated by else.
  • raise creates an exception, rescue handles it, after always runs, and defexception defines your own types.
  • throw and exit are rare; they are caught with catch.
  • Let it crash: validate at the edges, do not defend against your own bugs, and rely on supervisors for recovery.

Next, learn how Elixir does polymorphism: Protocols and Behaviours.