ZetCode

Ruby rescue Keyword

last modified October 18, 2026

This tutorial explains Ruby's rescue keyword for exception handling. It lets programs handle runtime errors instead of crashing.

The rescue keyword catches exceptions raised in Ruby code. It works with begin/end blocks, method definitions, and inline expressions. A rescue clause without an exception class catches StandardError and its descendants, but not Exception itself.

Exception handling separates normal program flow from error logic. This makes code more robust and maintainable. Ruby provides several related keywords.

Basic rescue Example

This simple example demonstrates catching a division by zero error. The rescue block prevents program termination.

basic_rescue.rb
begin
  result = 10 / 0
  puts "Result: #{result}"
rescue => e
  puts "Error occurred: #{e.message}"
end

The code attempts an invalid division, triggering a ZeroDivisionError. The rescue block catches it and prints the error message instead of crashing.

Rescuing Specific Exceptions

Ruby allows targeting specific exception classes. This provides precise control over different error types.

specific_rescue.rb
begin
  File.open("nonexistent.txt") do |file|
    puts file.read
  end
rescue Errno::ENOENT
  puts "File not found"
rescue IOError => e
  puts "IO error: #{e.message}"
end

Rescue clauses are checked in order. The first catches missing files with Errno::ENOENT, while the second handles a general IOError.

Inline rescue

Ruby supports a compact form where rescue modifies an expression. This provides default values when operations fail.

inline_rescue.rb
require "json"

value = Integer("abc") rescue 0
puts "Converted value: #{value}"

data = JSON.parse("invalid") rescue {}
puts "Parsed data: #{data.inspect}"

The rescue modifier provides a fallback when an expression raises a StandardError. It is convenient for simple defaults, but it can hide unexpected errors.

Ensure for Cleanup

The ensure clause always runs after the begin block, whether it succeeds, raises, or is rescued. It is ideal for resource cleanup.

ensure_clause.rb
file = nil
begin
  file = File.open("data.txt", "w")
  file.puts "Important data"
  raise "Simulated error"
rescue => e
  puts "Error writing file: #{e}"
ensure
  file.close if file
  puts "File handle closed"
end

The ensure block closes the file whether writing succeeds or fails. This avoids leaking the file handle.

Retry Mechanism

The retry keyword re-executes the begin block after rescue. This enables automatic recovery from transient failures.

retry_mechanism.rb
MAX_ATTEMPTS = 3
attempts = 0

begin
  attempts += 1
  puts "Attempt #{attempts}"
  raise "Network error"
rescue RuntimeError => e
  retry if attempts < MAX_ATTEMPTS
  puts "Giving up: #{e.message}"
end

The rescue block retries the failed operation until MAX_ATTEMPTS is reached, then gives up. Always limit retries; an unconditional retry on a persistent failure loops forever.

Rescue in Methods

Methods can use rescue without explicit begin/end blocks. This provides cleaner syntax for method-level error handling.

method_rescue.rb
def calculate_ratio(a, b)
  a / b
rescue ZeroDivisionError
  Float::INFINITY
rescue TypeError => e
  puts "Invalid input: #{e.message}"
  nil
end

puts calculate_ratio(10, 0)
puts calculate_ratio(10, "2")

The method handles division errors and type mismatches gracefully. Each rescue clause addresses a specific failure mode.

Custom Exceptions with Rescue

Ruby programs can define and rescue custom exception classes. This enables domain-specific error handling.

custom_exceptions.rb
class TemperatureError < StandardError; end

def check_temperature(temp)
  raise TemperatureError, "Too hot!" if temp > 40
  raise TemperatureError, "Too cold!" if temp < 10
  puts "Temperature OK"
rescue TemperatureError => e
  puts "Warning: #{e.message}"
end

check_temperature(45)
check_temperature(5)
check_temperature(25)

The custom TemperatureError class provides meaningful error categorization. Because it inherits from StandardError, a bare rescue clause also catches it. The rescue block handles all temperature-related issues uniformly.

Source

Ruby Exceptions Documentation

This tutorial covered Ruby's rescue keyword with examples showing basic usage, specific exceptions, inline syntax, and custom error handling.

Author

My name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming.

List all Ruby tutorials.