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:

  1. We define a module Recover that contains our functions.

  2. The may_raise/0 function simply raises an exception with the message “a problem”.

  3. In the main/0 function, we use a try-rescue block to handle potential exceptions:

    • The try block contains the code that might raise an exception.
    • The rescue clause catches any RuntimeError and prints the error message.
  4. If an exception is raised in the try block, execution immediately moves to the rescue clause, skipping any remaining code in the try block.

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