What is exception handling in Ruby?

Exception handling lets the user define the course of action in case an error is raised. When an error arises in the normal execution of the code, the alternative block of code is executed instead.

Ruby also provides a separate class for exceptions, the Exception class, which contains different types of methods.

Declaration

Particular keywords help with exception handling. The begin and end keywords enclose both the main block of code and the rescue block.

The main block of code is indented after the raise keyword, while the code to be executed in case of an error is indented after rescue.

Syntax

begin
    raise
      # block where an exception is raised

    rescue
      # block where exception is rescued
end

Multiple rescue clauses

If the exception is not handled by one rescue block, it will be handled by the next run of the rescue code, using the retry command. However, extra care is required with the retry statement as it may lead to an infinite loop.

Alternate path

We can use the else block to set up an alternate path for execution. If no exception is raised, the else block will run.

Ensured path

We can use the ensure path to hold code that must run, irrespective of whether an exception was raised or not.

Code

The following block of code shows how exception handling is done in Ruby:

# Example code for exception handling
# Exception handling block begins
begin
puts 'Start program...'
# using raise to create an exception
raise 'Raising exception here!'
puts 'After exception.'
# using Rescue method
rescue
puts 'Rescued exception!'
else # this block runs if no exception raises
puts "All okay."
ensure # this block always runs
puts "Ensure block."
# Exception handling block ends
end
puts 'Outside the exception handling block.'

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved