Recover in Elixir
In Elixir, we can use try
, rescue
, and catch
to handle exceptions, which is similar to the concept of panic and recover in other languages.
defmodule Recover do
# This function raises an exception.
def may_raise do
raise "a problem"
end
def main do
# In Elixir, we use try-rescue to handle exceptions.
try do
may_raise()
# This code will not run, because may_raise raises an exception.
# The execution stops at the point of the exception and moves to the rescue clause.
IO.puts("After may_raise()")
rescue
e in RuntimeError ->
# The rescue clause catches the exception.
# We can access the error message using e.message
IO.puts("Recovered. Error:\n #{e.message}")
end
end
end
# Run the main function
Recover.main()
In this Elixir code:
We define a module
Recover
that contains our functions.The
may_raise/0
function simply raises an exception with the message “a problem”.In the
main/0
function, we use atry-rescue
block to handle potential exceptions:- The
try
block contains the code that might raise an exception. - The
rescue
clause catches anyRuntimeError
and prints the error message.
- The
If an exception is raised in the
try
block, execution immediately moves to therescue
clause, skipping any remaining code in thetry
block.Finally, we call
Recover.main()
to run our code.
When you run this program, you’ll see the following output:
$ elixir recover.exs
Recovered. Error:
a problem
This demonstrates how Elixir can catch and handle exceptions, allowing your program to recover from errors and continue execution rather than crashing.