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
Recoverthat contains our functions.The
may_raise/0function simply raises an exception with the message “a problem”.In the
main/0function, we use atry-rescueblock to handle potential exceptions:- The
tryblock contains the code that might raise an exception. - The
rescueclause catches anyRuntimeErrorand prints the error message.
- The
If an exception is raised in the
tryblock, execution immediately moves to therescueclause, skipping any remaining code in thetryblock.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 problemThis demonstrates how Elixir can catch and handle exceptions, allowing your program to recover from errors and continue execution rather than crashing.