Exceptions
An exception in Elixir is an ordinary struct with a message, raised by raise/1 or raise/2. Raising stops the current function and unwinds the stack until a try or a rescue catches the value; with no catcher at all the program prints the exception and the stack and exits with a status of 1.
raise and rescue
raise "text" builds a RuntimeError with that message, and a try block with a rescue clause catches it. The clause names the variable and the type, and the exception is a struct, so its fields are read with a dot:
raise.exs
try do raise "something went wrong" rescue error in RuntimeError -> IO.puts("caught: #{error.message}") end
elixir raise.exs
caught: something went wrong
The rescued value is the exception, not a string, and error.message is the field the Exception behaviour defines. A clause with no type catches every exception, which is the form a program uses only at the top of a call tree, where it reports rather than hides the failure.
An exception of the program
defexception declares an exception type in one line, with the fields it carries; :message is the one field every exception has. The clause that catches it can read the other fields, which is how an error carries a code and not only a sentence:
apperror.exs
defmodule AppError do defexception [:message, :code] end try do raise AppError, message: "not found", code: 404 rescue error in AppError -> IO.inspect({error.message, error.code}) end
elixir apperror.exs
{"not found", 404}
A module of the program that raises its own type lets the caller catch exactly that type and let the rest through. The struct is also the place for a function that builds the message from the data, which is the exception/1 callback of the behaviour; the lesson on raise or return is about when a library raises at all.
rescue in a function body
A function may carry its own rescue clause, written at the end of the body like a private try. The clause below turns the parse error into a value the caller can handle, which is the shape of a function that is allowed to fail:
several.exs
defmodule Parse do def int(text) do String.to_integer(text) rescue ArgumentError -> :not_a_number end end IO.inspect(Parse.int("42")) IO.inspect(Parse.int("x"))
elixir several.exs
42
:not_a_number
The rescue covers the body and not the caller, so a failure in Parse.int/1 is answered while a failure elsewhere is not. Several clauses may name several types, and e in [ArgumentError, ArithmeticError] is the shorter spelling for two of them.
The stack trace of a crash
An exception that nobody catches prints its message and the frames that led to it, newest first. The message says what was wrong, and the frames say where: the function that raised and the line that called it:
mistake.exs
defmodule Reader do def id(n) when is_integer(n), do: n def id(text) do raise ArgumentError, "the id must be a number, got: #{inspect(text)}" end end Reader.id("abc")
elixir mistake.exs
** (ArgumentError) the id must be a number, got: "abc"
mistake.exs:5: Reader.id/1
mistake.exs:9: (file)
The first frame is where the raise happened and the second is the call. A message that includes the value, built with inspect/1, is what makes a crash report useful: the reader sees which id was wrong without opening the code. The status of the run is 1, which is what a script and a pipeline test.
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.
-
What does
raise "text"create?Answer
a RuntimeError with that message
A string given to raise becomes a RuntimeError, which is the general exception of the language.
-
What does a
rescueclause receive?Answer
the exception struct
The rescued value is the exception, so its fields are read with a dot.
-
What does
defexceptiondeclare?Answer
an exception type with its fields
The macro declares a module that implements the Exception behaviour with the fields named.
-
What is the first frame of a crash trace?
Answer
the function and line where the raise happened
The newest frame comes first, which is the place the exception was raised.
-
What does this program print?
try do raise "boom" rescue e in RuntimeError -> IO.puts(e.message) endAnswer
boom
The clause catches the RuntimeError and prints its message, which is the text of the raise.
-
What does this program print?
defmodule E do defexception [:message, :code] end try do raise E, message: "no", code: 7 rescue e in E -> IO.inspect({e.message, e.code}) endAnswer
{"no", 7}
The struct carries both fields from the raise, and the clause reads them.
-
What does this program print?
defmodule P do def int(text) do String.to_integer(text) rescue ArgumentError -> :bad end end IO.inspect(P.int("x"))Answer
:bad
The rescue clause of the function answers the atom instead of letting the error out.
-
What does a program do when nothing catches its exception?
Answer
It prints the message and the stack and exits with status 1
The runtime reports the exception and the frames, which is what a crash report is.
-
Why does an exception message include
inspect/1of the bad value?Answer
so the report shows which value was wrong
The reader sees the value that caused the failure without opening the code.
-
What does this program do?
raise ArgumentError, "the id must be a number"Answer
An ArgumentError, because nothing catches the raise
No clause catches it, so the runtime prints the exception and stops with a failure status.
Article author: Arthur Isaev