Recover in Ruby

Ruby makes it possible to rescue from an exception, which is similar to recovering from a panic in other languages. A rescue clause can stop an exception from aborting the program and let it continue with execution instead.

An example of where this can be useful: a server wouldn’t want to crash if one of the client connections exhibits a critical error. Instead, the server would want to close that connection and continue serving other clients.

# This method raises an exception.
def may_raise_exception
  raise "a problem"
end

# The rescue clause must be within the method or block where the exception might occur.
# When the enclosing method raises an exception, the rescue clause will
# catch the exception.
def main
  # The rescued exception is available in the rescue clause.
  begin
    may_raise_exception
  rescue => e
    puts "Rescued. Error:\n #{e}"
  end

  # This code will not run, because may_raise_exception raises an exception.
  # The execution of main stops at the point of the exception and resumes in the rescue clause.
  puts "After may_raise_exception()"
end

main

When you run this program, you’ll see:

$ ruby recover.rb
Rescued. Error:
 a problem

In Ruby, exceptions are used for error handling, which is similar to panics in some other languages. The begin/rescue block in Ruby serves a similar purpose to defer/recover in those languages. It allows you to catch and handle exceptions, preventing them from crashing your program.

Remember that while this error handling is powerful, it should be used judiciously. Rescuing from too broad a range of exceptions can make bugs harder to detect and debug.