Ruby Exception Handling — begin, rescue, ensure — Complete Beginner Guide
Learning Objectives
- Raise and catch exceptions with raise and rescue
- Structure handlers with begin and rescue blocks
- Guarantee cleanup actions with ensure
- Create custom exception classes
- Write error handling that stays specific and useful
What Is an Exception
An exception is an object describing something that went wrong during execution. When Ruby encounters an unrecoverable problem such as dividing by zero or reading a missing file, it raises an exception and unwinds the stack until a handler catches it.
begin
puts 10 / 0
rescue => e
puts "Problem: #{e.message}"
end
The rescue clause captures the exception, preventing an immediate crash and giving you a chance to respond.
The begin and rescue Structure
begin marks the code to protect, and rescue handles failures.
begin
number = Integer("not a number")
rescue ArgumentError => e
puts "Could not parse: #{e.message}"
end
You can rescue specific exception classes for precise handling. Catching narrower errors first keeps unrelated failures visible instead of silently swallowed.
Multiple rescue clauses
begin
risky_work
rescue ArgumentError
puts "Bad input"
rescue Timeout::Error
puts "Too slow"
end
Ruby matches the most specific applicable clause. Order matters when exception classes share inheritance.
Ensuring Cleanup With ensure
ensure runs whether the protected code succeeded or failed. Use it for releasing resources, closing files, or logging completion.
begin
puts "Working..."
raise "Boom"
rescue => e
puts "Caught #{e.message}"
ensure
puts "Cleanup always runs"
end
ensure is ideal for tasks that must happen regardless of outcome, mirroring finally patterns in other languages.
Method-level ensure
You can also attach rescue and ensure directly to method definitions without an explicit begin block, keeping syntax compact.
Raising Exceptions
Raise an exception yourself when input is invalid or a precondition fails.
def withdraw(amount)
raise ArgumentError, "Amount must be positive" if amount <= 0
puts "Withdrawing #{amount}"
end
begin
withdraw(-5)
rescue ArgumentError => e
puts e.message
end
Raise with a clear message so future you, or a teammate reading logs, understands exactly what failed and why.
Common Built-in Exceptions
| Exception | Typical cause |
|---|---|
| ArgumentError | Wrong argument values |
| TypeError | Wrong data type |
| NoMethodError | Calling a missing method |
| NameError | Undefined variable or constant |
| IOError | File operation problems |
| ZeroDivisionError | Division by zero |
Knowing these names helps you write targeted rescue clauses.
Custom Exception Classes
Domain-specific errors improve clarity. Create your own by inheriting from StandardError.
class OutOfStockError < StandardError
end
def buy(item)
raise OutOfStockError, "#{item} is unavailable" if item == "rare"
puts "Purchased #{item}"
end
begin
buy("rare")
rescue OutOfStockError => e
puts e.message
end
Custom classes let callers rescue exactly your error while ignoring unrelated failures.
Retry and Recovery
rescue blocks can attempt recovery, including retrying the operation.
attempts = 0
begin
attempts += 1
raise "Temporary failure" if attempts < 2
puts "Succeeded"
rescue
retry if attempts < 3
puts "Giving up"
end
Guard retries with a limit to avoid infinite loops when failures persist.
What to Avoid
- Rescuing StandardError with a bare rescue and ignoring the result
- Catching exceptions you cannot meaningfully handle
- Swallowing errors silently, which hides real bugs
- Using exceptions for routine control flow when conditionals would do
Good exception handling communicates failure clearly and keeps recovery logic close to the problem.
Error Classes and Custom Exceptions
Ruby organizes exceptions into a hierarchy rooted at Standard Error. You can rescue specific classes to handle only the errors you expect while letting unexpected ones bubble up for debugging. Defining your own exception classes lets you raise domain specific errors with meaningful names, making rescue blocks in calling code more precise and self documenting.
Rescue Else and Ensure
The else clause runs only when no exception was raised, giving you a clean place for success path logic. The ensure clause always runs whether an exception occurred or not, making it perfect for cleanup tasks like closing files or releasing locks. Together these clauses give you fine grained control over every outcome of a protected block of code.
Nesting begin blocks lets you handle different error types at different levels of your program. An inner rescue might retry a transient network failure, while an outer rescue logs the error and returns a graceful fallback to the user. This layered approach keeps error handling proportional to the scope of each concern.
Retry and Recovery Patterns
Inside a rescue block you can retry the beginning of the protected section to attempt the operation again after a transient failure. Combining retry with a counter prevents infinite loops when errors persist. This pattern is common when talking to flaky network services where a single quick retry often succeeds without bothering the end user with an error message.
Key Takeaways
💡
- begin wraps risky code; rescue catches exceptions; ensure always runs
- raise signals failure with informative messages
- Rescue specific exception classes rather than catching everything
- Custom exceptions inherit from StandardError for clean handling
- Never silently discard errors without logging or recovery
Practice Questions
- Write a begin/rescue block that handles a ZeroDivisionError.
- What is the purpose of ensure?
- Create a custom exception for invalid email input and raise it.
- Why should you avoid a bare rescue with no follow-up handling?
- How does Ruby decide which rescue clause matches an exception?
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type — Always start by categorizing the problem
- Incorrect formula application — Verify the formula applies to your specific case
- Unit errors — Always check units are consistent throughout
- Sign errors — Pay careful attention to positive and negative values
- Rounding too early — Keep full precision until the final answer
- Forgetting constraints — Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic — Build on the foundation laid here
- Next Topic — See how this concept extends to more advanced material
- Practice Problems — Additional exercises with solutions
- Video Explanation — Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions