0
0
Rubyprogramming~5 mins

Multiple rescue clauses in Ruby

Choose your learning style9 modes available
Introduction
Sometimes, different errors need different ways to fix them. Multiple rescue clauses let you handle each error separately.
When you want to handle different errors in different ways.
When your code might fail for several reasons and you want clear fixes.
When you want to show different messages for different problems.
Syntax
Ruby
begin
  # code that might cause errors
rescue ErrorType1
  # handle ErrorType1
rescue ErrorType2
  # handle ErrorType2
else
  # runs if no error
ensure
  # always runs
end
You can have many rescue clauses to catch different error types.
The ensure block runs no matter what, even if there is an error.
Examples
This code catches division by zero specifically, and any other error generally.
Ruby
begin
  1 / 0
rescue ZeroDivisionError
  puts "Can't divide by zero!"
rescue StandardError
  puts "Some other error happened."
end
Different errors from file operations are handled separately.
Ruby
begin
  file = File.open('missing.txt')
rescue Errno::ENOENT
  puts "File not found!"
rescue IOError
  puts "IO error happened!"
end
Sample Program
This program asks for a number and divides 10 by it. It handles zero division and invalid input separately.
Ruby
begin
  puts "Enter a number:"
  num = Integer(gets.chomp)
  result = 10 / num
  puts "10 divided by your number is #{result}"
rescue ZeroDivisionError
  puts "Oops! You can't divide by zero."
rescue ArgumentError
  puts "That's not a valid number."
end
OutputSuccess
Important Notes
Order matters: Ruby checks rescue clauses from top to bottom and stops at the first match.
Use specific error classes first, then more general ones later.
You can use rescue without specifying an error to catch all StandardError exceptions.
Summary
Multiple rescue clauses let you handle different errors in different ways.
Write rescue clauses from specific to general errors.
Use ensure to run code no matter what happens.