How to Handle Exceptions Using Begin and Rescue in Ruby

Nurudeen Ibrahim Feb 02, 2024
  1. General Syntax of Exception Handling in Ruby
  2. Handle Exceptions Using begin and rescue in Ruby
How to Handle Exceptions Using Begin and Rescue in Ruby

This article will discuss handling exceptions using begin and rescue in Ruby.

General Syntax of Exception Handling in Ruby

In Ruby, the begin and rescue keywords handle exceptions by enclosing the code that may raise an exception in a begin-end block.

begin
  # code that might raise an exception
rescue AnExceptionClass => e
  # code that deals with some exception
rescue AnotherException => e
  # code that deals with another exception
else
  # code that runs only if no exception was raised

  # code that always runs no matter what
end

Handle Exceptions Using begin and rescue in Ruby

The example below shows the begin and rescue keywords.

Example code:

def do_arithmetic(a, b)
  answer = (b + a) / (a * b)
  puts answer
rescue ZeroDivisionError => e
  puts "Custom Error: #{e.message}"
rescue TypeError => e
  puts "Custom Error: #{e.message}"
ensure
  puts 'Done.'
end

do_arithmetic(2, 2)
do_arithmetic(0, 2)
do_arithmetic('David', 2)

Output:

# first output
1
Done.

# second output
Custom Error: divided by 0
Done.

# third output
Custom Error: String can't be coerced into Integer
Done.

Combining multiple exceptions and handling them in the same rescue block is also possible. The ZeroDivisionError, and the TypeError exceptions in the above example can be run together below.

def do_arithmetic(a, b)
  answer = (b + a) / (a * b)
  puts answer
rescue ZeroDivisionError, TypeError => e
  puts "Custom Error: #{e.message}"
ensure
  puts 'Done.'
end

Related Article - Ruby Exception