How to Handle Exceptions in Ruby



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:

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

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:

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

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.