O'Reilly logo

Programming Elixir by Dave Thomas

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

catch, exit, and throw

Elixir code (and the underlying Erlang libraries) can raise a second kind of error. These are generated when a process calls error, exit, or throw. All three take a parameter, which is available to the catch handler.

Here’s an example:

exceptions/catch.ex
 
defmodule​ Catch ​do
 
 
def​ start(n) ​do
 
try​ ​do
 
incite(n)
 
catch
 
:exit, code -> ​"Exited with code #{inspect code}"
 
:throw, value -> ​"throw called with #{inspect value}"
 
what, value -> ​"Caught #{inspect what} with #{inspect value}"
 
end
 
end
 
 
 
defp​ incite(1) ​do
 
exit​(:something_bad_happened)
 
end
 
 
defp​ incite(2) ​do
 
throw​ {:animal, ​"wombat"​}
 
end
 
 
defp​ incite(3) ​do
 
:erlang.error ​"Oh no!"
 
end ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required