Panic in Elixir
In Elixir, we use exceptions to handle unexpected errors or situations that shouldn’t occur during normal operation. This is similar to the concept of panic
in other languages.
defmodule PanicExample do
def main do
# We'll use raise throughout this site to check for
# unexpected errors. This is the only program on the
# site designed to raise an exception.
raise "a problem"
# A common use of raise is to abort if a function
# returns an error value that we don't know how to
# (or want to) handle. Here's an example of
# raising an exception if we get an unexpected error when creating a new file.
case File.open("/tmp/file", [:write]) do
{:ok, file} ->
IO.puts("File created successfully")
File.close(file)
{:error, reason} ->
raise "Failed to create file: #{reason}"
end
end
end
PanicExample.main()
Running this program will cause it to raise an exception, print an error message and stacktrace, and exit with a non-zero status.
When the first raise
in main
is executed, the program exits without reaching the rest of the code. If you’d like to see the program try to create a temp file, comment out the first raise
.
$ elixir panic_example.exs
** (RuntimeError) a problem
panic_example.exs:6: PanicExample.main/0
Note that in Elixir, it’s idiomatic to use pattern matching and the {:ok, result}
/ {:error, reason}
tuple convention for handling many errors, rather than raising exceptions for every possible error condition. Exceptions are typically used for truly exceptional situations that prevent the normal flow of the program.