Ruby Logo

Exception-handling

Learn about exception-handling in Ruby programming.

Home Ruby Exception-handling

Ruby Exception Handling Mastery

Master Ruby's exception handling system with begin/rescue/ensure/end blocks, raise statements, and custom exceptions. Learn how to write robust, error-resistant code that gracefully handles unexpected situations.

Understanding Exceptions

Exception: An object that represents an error or unexpected condition that occurs during program execution. Instead of crashing, Ruby allows you to "catch" and handle these exceptions gracefully.

Real-World Analogy

Think of exceptions like fire safety systems: Just as buildings have fire alarms, sprinklers, and emergency exits to handle fires gracefully (instead of just burning down), your code should have exception handling to deal with errors without crashing.

🚀 Interactive Practice

Interactive Code Runner

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

🎯 Key Takeaways

  • begin/rescue/end: Basic exception handling structure
  • ensure clause: Always runs, perfect for cleanup
  • raise: Manually trigger exceptions with meaningful messages
  • Exception objects: Contain class, message, and backtrace information

Exception handling in Ruby allows you to gracefully manage errors and unexpected conditions. Master begin/rescue/ensure blocks, raise statements, and custom exceptions for robust applications.

Basic Exception Handling

Exception Handling: Use begin/rescue/ensure blocks to catch and handle exceptions gracefully, ensuring your application continues running even when errors occur.

Basic begin/rescue Block

# Basic exception handling
begin
result = 10 / 0
rescue
ZeroDivisionError => e
puts "Error: \#{e.message}"
result = 0
end

puts
result
# 0

Multiple Exception Types

# Handling multiple exception types
def
safe_divide
(a, b)
begin
a / b
rescue
ZeroDivisionError
puts "Cannot divide by zero"
0
rescue
TypeError
puts "Invalid input types"
0
end
end

puts
safe_divide(10, 2)
# 5
puts
safe_divide(10, 0)
# 0

Ensure Block

# Using ensure for cleanup
def
read_file_safely
(filename)
file = nil
begin
file = File.open(filename)
file.read
rescue
Errno::ENOENT
puts "File not found: \#{filename}"
nil
ensure
file.close if file
end
end

Raising Exceptions

Raising Exceptions: Use the 'raise' keyword to signal errors and exceptional conditions in your code.

Basic raise Statement

# Raising exceptions
def
validate_age
(age)
raise "Age must be positive" if age < 0
raise "Age must be less than 150" if age > 150
puts "Valid age: \#{age}"
end

begin
validate_age(25)
rescue
RuntimeError => e
puts "Error: \#{e.message}"
end

Raising Specific Exception Types

# Raising specific exception types
def
withdraw
(amount, balance)
raise
ArgumentError
, "Amount must be positive" if amount <= 0
raise
RuntimeError
, "Insufficient funds" if amount > balance
balance - amount
end

begin
result = withdraw(100, 50)
rescue
ArgumentError => e
puts "Argument error: \#{e.message}"
rescue
RuntimeError => e
puts "Runtime error: \#{e.message}"
end

Interactive Practice: Exception Handling

Practice Time: Try these exception handling 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

  • Use specific exception types when possible
  • Always use ensure for cleanup operations
  • Provide meaningful error messages
  • Handle exceptions at the appropriate level
  • Use rescue modifiers for simple cases
  • Log exceptions for debugging

❌ Common Pitfalls

  • Rescuing Exception instead of specific types
  • Swallowing exceptions without handling
  • Not cleaning up resources in ensure
  • Using exceptions for control flow
  • Not providing context in error messages
  • Overusing exception handling

Exception Handling Mastery Summary

You've Mastered Ruby Exception Handling!

Exception Handling

begin/rescue/ensure blocks

Raising Exceptions

raise keyword and error signaling

Error Recovery

Graceful error handling and cleanup

Exception handling is crucial for building robust Ruby applications. Use it wisely to handle errors gracefully while maintaining application stability and providing meaningful feedback to users.

Management
Exception Hierarchy & Error Objects

Quick Navigation

Read Topic
Watch Video Tutorial

Related Topics

Variables & Constants → Arrays → Methods →

Back to Ruby Home

Video Tutorial

Watch and learn exception-handling

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