Limited Offer
60% OFF on all plans!

Error / Exception Handling in Ruby

Handle runtime errors gracefully using begin, rescue, ensure, retry, and raise in Ruby.

Introduction to Exceptions

In Ruby, errors are called exceptions. When something goes wrong at runtime, Ruby raises an exception — an instance of an Exception subclass. If not rescued, the program terminates with an error message and backtrace.

1. What Is an Exception?

Ruby raises an exception when it cannot continue execution.

Common Exception Types

All Ruby exceptions inherit from `Exception`. Most runtime errors inherit from `StandardError` — which is the default class rescued by `rescue` with no argument.

1. NameError

Undefined variable or method.

2. TypeError

Invalid operation on a wrong type.

3. ArgumentError

Wrong number or type of arguments passed to a method.

4. ZeroDivisionError

Division by zero.

5. IndexError / KeyError

Invalid index or missing hash key.

begin / rescue

The `begin/rescue` block is Ruby's equivalent of try/catch. Code in `begin` is attempted, and `rescue` runs if an exception is raised.

1. Basic begin / rescue

Prevent crashes by rescuing exceptions.

2. Rescuing a Specific Exception

Rescue only the exceptions you expect.

3. Rescuing Multiple Types in One Line

Handle several exception types with a single rescue.

ensure — Always Runs

`ensure` is Ruby's equivalent of `finally` — it always runs whether or not an exception occurred. Use it to close files, release connections, or clean up resources.

1. ensure Block

Guaranteed cleanup code.

raise — Throwing Exceptions

`raise` in Ruby is equivalent to `throw` in JS or `raise` in Python. It stops execution and propagates an exception up the call stack.

1. raise with a Message

Raise a RuntimeError with a custom message.

2. raise with a Specific Class

Use a specific exception class for clarity.

3. retry — Retry After Rescue

Retry the begin block after handling an error.

Custom Exception Classes

Custom exceptions make your code's failure modes explicit and allow callers to rescue specific errors. Inherit from `StandardError` (not `Exception`) for application errors.

1. Creating a Custom Exception

Subclass StandardError.

2. Rescue Hierarchy

A parent class rescue catches all subclasses.

Inline Rescue & Method-Level Rescue

Ruby allows `rescue` directly in a method body (no `begin` needed) and also as an inline one-liner for simple fallbacks.

1. rescue in Method Body

The entire method body acts as the begin block.

2. Inline rescue Operator

One-liner fallback value on error.