Trying, Rescuing, and Catching
Learn to handle exceptions in Elixir.
We'll cover the following...
Introduction to error handling in Elixir
Some functions raise errors or throw values as we don’t control the code. We need the try
statement to handle the unexpected results. If you came from object-oriented languages like C++, Java, and Ruby, this technique will be familiar.
Most of the time, we can easily identify the functions that can raise errors or throw values because their names end with an exclamation point. For example, the File.cd!/1
function raises an exception when the path doesn’t exist.
The try
statement wraps a code block. If an error is raised, we can use rescue
to recover. An error or exception in Elixir is a special data structure that describes when an exceptional thing happens in the code. We can also use try
to capture values with catch
because Elixir functions can stop their execution by sending a value with the throw
directive.
Throwing values or raising errors is unusual in functional programming. However, in large applications, we’ll install libraries from other developers that use this strategy, and we need to know how to handle the raised errors and thrown values properly. In this lesson, we’ll see the try
, raise
, and rescue
combination for exceptions, and the try
, ...