Ruby Logo

Exception-hierarchy

Learn about exception-hierarchy in Ruby programming.

Home Ruby Exception-hierarchy

Ruby Exception Hierarchy Mastery

Understanding Ruby's exception hierarchy is crucial for effective error handling. Learn about StandardError, RuntimeError, and how to create custom exception classes for better error management.

Exception Hierarchy Overview

Exception Hierarchy: Ruby's exception system is organized in a hierarchy where more specific exceptions inherit from more general ones, allowing for flexible error handling.

Ruby Exception Hierarchy Tree

# Ruby Exception Hierarchy
Exception
├── SystemExit
├── SystemStackError
├── NoMemoryError
├── SecurityError
├── ScriptError
│ ├── LoadError
│ ├── NotImplementedError
│ └── SyntaxError
├── StandardError
│ ├── ArgumentError
│ ├── IOError
│ ├── RuntimeError
│ ├── NameError
│ │ └── NoMethodError
│ ├── IndexError
│ │ └── StopIteration
│ ├── TypeError
│ ├── ZeroDivisionError
│ └── SystemCallError
└── Interrupt

Key Exception Types

# Common exception types and their uses
begin
# RuntimeError - default for raise
raise "Something went wrong"
rescue
RuntimeError => e
puts "Runtime error: \#{e.message}"
end

begin
# ArgumentError - invalid arguments
raise
ArgumentError
, "Invalid argument"
rescue
ArgumentError => e
puts "Argument error: \#{e.message}"
end

begin
# TypeError - wrong object type
1 + "string"
rescue
TypeError => e
puts "Type error: \#{e.message}"
end

StandardError vs Exception

Important Distinction: Always rescue StandardError, not Exception. Exception includes system-level errors that should not be caught in normal application code.

Correct Exception Handling

# ✅ CORRECT: Rescue StandardError
begin
# Your application code
10 / 0
rescue
StandardError => e
puts "Application error: \#{e.message}"
end

# ❌ WRONG: Don't rescue Exception
begin
# Your application code
10 / 0
rescue
Exception => e
puts "This catches system errors too!"
end

Why StandardError?

# System errors that should NOT be caught:
puts "SystemExit: \#{SystemExit < Exception}"
# true
puts "NoMemoryError: \#{NoMemoryError < Exception}"
# true
puts "SystemStackError: \#{SystemStackError < Exception}"
# true

# Application errors that SHOULD be caught:
puts "RuntimeError: \#{RuntimeError < StandardError}"
# true
puts "ArgumentError: \#{ArgumentError < StandardError}"
# true
puts "ZeroDivisionError: \#{ZeroDivisionError < StandardError}"
# true

Custom Exception Classes

Custom Exceptions: Create domain-specific exception classes that inherit from StandardError for better error handling and debugging.

Basic Custom Exception

# Basic custom exception class
class
ValidationError
<
StandardError
def initialize(message = "Validation failed")
super(message)
end
end

def
validate_email
(email)
raise
ValidationError
, "Invalid email format" unless email.include?("@")
puts "Email is valid: \#{email}"
end

Advanced Custom Exception

# Advanced custom exception with context
class
APIError
<
StandardError
attr_reader :status_code, :response_body
def initialize(message, status_code = 500, response_body = nil)
super(message)
@status_code = status_code
@response_body = response_body
end
def to_s
"\#{super} (Status: \#{@status_code})"
end
end

def
make_api_request
(url)
# Simulate API call
raise
APIError
.new("Server error", 500, "Internal server error")
end

Interactive Practice: Exception Hierarchy

Practice Time: Try these exception hierarchy examples. Understanding these patterns will make you a more effective Ruby programmer.

Interactive Code Runner

Ruby Code Editor
Output will appear here when you run the code...

Best Practices & Common Patterns

✅ Best Practices

  • Always inherit from StandardError, not Exception
  • Use specific exception types for different errors
  • Provide meaningful error messages
  • Include context information in custom exceptions
  • Use exception hierarchy for error classification
  • Document custom exception behavior

❌ Common Pitfalls

  • Inheriting from Exception instead of StandardError
  • Creating too many custom exception classes
  • Not providing enough context in error messages
  • Using generic exception types everywhere
  • Not following naming conventions
  • Overcomplicating exception hierarchies

Exception Hierarchy Mastery Summary

You've Mastered Ruby Exception Hierarchy!

Exception Hierarchy

StandardError vs Exception distinction

Custom Exceptions

Domain-specific error classes

Error Classification

Organized error handling

Understanding Ruby's exception hierarchy is essential for effective error handling. Use StandardError for application errors and create custom exceptions for domain-specific error conditions.

Quick Navigation

Related Topics

Video Tutorial

Watch and learn exception-hierarchy

Pro Tip: After reading through the content above, watch this video to reinforce your understanding and see the concepts in action!