Exceptions help your program handle errors without crashing. The exception hierarchy organizes these errors so you can catch and fix them easily.
0
0
Exception hierarchy in Ruby
Introduction
When you want to handle different types of errors in your program.
When you want to catch all errors that come from a common group.
When you want to create your own error types that fit into Ruby's error system.
Syntax
Ruby
begin # code that might cause an error rescue ExceptionType => e # code to handle the error end
begin starts the block where errors might happen.
rescue catches errors of a specific type or its subtypes.
Examples
This catches the error when dividing by zero.
Ruby
begin 1 / 0 rescue ZeroDivisionError => e puts "Cannot divide by zero!" end
This catches an error when accessing an invalid array index.
Ruby
begin [].fetch(1) rescue IndexError => e puts "Index is out of range!" end
This raises and catches a general standard error.
Ruby
begin raise StandardError, "Oops!" rescue StandardError => e puts e.message end
Sample Program
This program tries to open a file that does not exist. It catches different errors based on Ruby's exception hierarchy.
Ruby
begin puts "Trying to open a file..." File.open("nonexistent.txt") rescue IOError => e puts "IO error happened: #{e.message}" rescue SystemCallError => e puts "System call error happened: #{e.message}" rescue Exception => e puts "Some other error: #{e.message}" end
OutputSuccess
Important Notes
All error classes in Ruby inherit from Exception.
StandardError is the default for rescue if no exception type is given.
Use specific exceptions first, then more general ones to avoid catching errors too broadly.
Summary
Exceptions are organized in a hierarchy starting from Exception.
You can catch errors by their type or any of their parent types.
Handling exceptions helps keep your program running smoothly even when errors happen.