🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Ruby Exception Handling — begin, rescue, ensure — Complete Beginner Guide

Ruby BasicsRuby Exception Handling🟢 Free Lesson

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

ExceptionTypical cause
ArgumentErrorWrong argument values
TypeErrorWrong data type
NoMethodErrorCalling a missing method
NameErrorUndefined variable or constant
IOErrorFile operation problems
ZeroDivisionErrorDivision 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

  1. Write a begin/rescue block that handles a ZeroDivisionError.
  2. What is the purpose of ensure?
  3. Create a custom exception for invalid email input and raise it.
  4. Why should you avoid a bare rescue with no follow-up handling?
  5. 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

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. 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

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. 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

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids 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
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Ruby Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement