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:

 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) ...

Get Programming Elixir ≥ 1.6 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.