Exceptions

Understand the exceptions and their implementation in different cases in Elixir programming.

Raising exceptions

First, the official warning: exceptions in Elixir are not control-flow structures. Instead, Elixir exceptions are intended for things that should never happen in normal operation. That means the database going down or a name server failing to respond could be considered exceptional. Failing to open a configuration file whose name is fixed could be seen as exceptional. However, failing to open a file whose name a user entered is not.

We raise an exception with the raise function. At its simplest level, we pass it a string, and it generates an exception of type RuntimeError.

iex> raise "Giving up"
** (RuntimeError) Giving up

We can also pass the type of exception, along with other optional attributes. All exceptions implement at least the message attribute.

iex> raise RuntimeError
** (RuntimeError) runtime error
iex> raise RuntimeError, message: "override message" 
** (RuntimeError) override message

We use exceptions far less in Elixir than in other languages. The design philosophy is that errors should propagate back up to an external supervising process.

Let’s practice these exceptions here:

Get hands-on with 1400+ tech skills courses.