How to Handle Exceptions in Ruby

09/20/2021

Contents

In this article, you will learn how to handle exceptions in Ruby.

Handling exceptions

In Ruby, exceptions are objects that represent an error or abnormal condition that occurs during the execution of a program. Exception handling is the process of detecting and responding to these errors in a way that maintains the stability and reliability of the program.

Here is an example of how to handle exceptions in Ruby:

begin
  # code that may raise an exception
rescue ExceptionType1
  # code to handle ExceptionType1
rescue ExceptionType2
  # code to handle ExceptionType2
else
  # code to execute if no exceptions were raised
ensure
  # code to execute regardless of whether an exception was raised
end

In this example, the begin block contains the code that may raise an exception. If an exception is raised, the program jumps to the appropriate rescue block, depending on the type of exception that was raised. If no exceptions are raised, the program executes the else block. The ensure block is always executed, regardless of whether an exception was raised or not.

Here is a more concrete example:

begin
  result = 10 / 0
rescue ZeroDivisionError => e
  puts "Error occurred: #{e.message}"
else
  puts "Result is: #{result}"
ensure
  puts "Execution complete"
end

In this example, the result = 10 / 0 line will raise a ZeroDivisionError exception because it attempts to divide by zero. The program will jump to the rescue block, where the error message will be printed. The else block will not be executed, since an exception was raised. Finally, the ensure block will be executed to indicate that the program has finished running.

It’s important to note that the rescue block will only catch exceptions of the specified type. If you want to catch all types of exceptions, you can use rescue Exception, but this is generally discouraged since it can catch exceptions that you didn’t intend to catch. It’s better to be specific about the types of exceptions you want to catch.