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
 end

Calling the start function with 1, 2, or 3 will cause an exit, a throw, or an error to be thrown. Just to illustrate wildcard pattern matching, we handle the last case by matching any type into the variable what.

 iex>​ c(​"​​catch.ex"​)
 [Catch]
 iex>​ Catch.start 1
 "Exited with code :something_bad_happened"
 iex>​ Catch.start 2
 "throw called with {:animal,\"wombat\"}"
 iex>​ Catch.start 3
 "Caught :error with \"Oh no!\""