Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 134 ยท Control Flow

Exceptions

Learn Ruby exception handling - begin/rescue/else/ensure, raise, retry, the exception hierarchy, rescue modifiers, backtraces and full_message, with runnable examples.

Things go wrong: a file is missing, a string is not a number, you divide by zero, a hash lacks a key. Ruby does not return error codes for these situations. It raises an exception, an object that describes the problem, and unwinds the call stack until some code says "I know how to handle this". If nobody does, the program stops and prints the exception with its backtrace.

This lesson shows how to read Ruby's error messages, how to catch exceptions with begin/rescue, what else and ensure are for, how to raise your own, how retry works, and the habits that separate careful Ruby code from fragile code. Custom exception classes get their own lesson (Custom Exceptions).

An uncaught exception

Before handling errors, learn to read one. The next program fails on purpose.

Ruby An uncaught exception (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The first call prints 6. The second divides 0 by 0, and Ruby prints a message like main.rb:2:in 'Integer#/': divided by 0 (ZeroDivisionError), followed by the call chain (from main.rb:2:in 'Object#average' and so on). Read it left to right: the file and line, the method that was running, the message, and in parentheses the class of the exception. The last line never runs, because an unhandled exception ends the program with a non-zero exit code.

begin, rescue and the exception object

Wrap risky code in begin ... rescue ... end. When something inside raises, Ruby jumps to the matching rescue clause.

Ruby begin and rescue

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

rescue ZeroDivisionError => e catches that class and stores the exception object in e. Useful methods on it:

  • message: the human-readable text;
  • class: what kind of problem it is;
  • backtrace: an array of strings, newest call first (or nil if the exception was never raised);
  • full_message: message, class and backtrace formatted like Ruby's own crash output;
  • cause: the exception that was being handled when this one was raised (see below).

Inside a method body, def ... end is itself a begin block, so you can write rescue directly without an extra begin:

Ruby rescue inside a method

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Integer("forty-two") raises ArgumentError with the message invalid value for Integer(): "forty-two". The method turns that into nil. Blocks (do ... end) support the same direct rescue too.

Several rescue clauses

Handle different failures differently. Ruby checks the clauses from top to bottom and runs the first one that matches. List more specific classes first.

Ruby Choosing a rescue clause

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Notice that one rescue can list several classes, and that the last clause, StandardError, catches everything the earlier ones did not. The .each do ... rescue ... end form works because a block can have its own rescue. Run it and read the real messages: nil.upcase produces a NoMethodError whose message starts with undefined method 'upcase' for nil, and fetch produces a KeyError that names the missing key. Both messages are written to help you, so print them while debugging.

The exception hierarchy

Every exception is an instance of a class descending from Exception. The ones you handle in normal programs live under StandardError.

Ruby Walking up the exception hierarchy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The output shows that ZeroDivisionError < StandardError < Exception, that KeyError inherits from IndexError, and that NoMethodError inherits from NameError. A bare rescue (with no class) catches StandardError and its subclasses. That is deliberate: classes outside that branch, such as NoMemoryError, SystemExit (raised by exit), Interrupt (Ctrl+C) and SecurityError, signal conditions your code should usually let through.

Never write rescue Exception. It also catches SystemExit and Interrupt, so the program can no longer be stopped with exit or Ctrl+C, and it hides bugs such as typos in method names. Rescue the narrowest class you can name; use StandardError only at the outer edge (for example, a job runner that must log a failure and continue).

else and ensure

A full begin block can have four parts:

  1. the code that might fail;
  2. rescue clauses for failures;
  3. else, which runs only if nothing was raised;
  4. ensure, which runs always: after success, after a rescued error and even when an exception is on its way out.
Ruby rescue, else and ensure together

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Pay attention to the printed order for each call. The else branch runs only for "12", the rescue branch only for "zz", and ensure for both. The method's return value comes from the last expression of the branch that ran (else or rescue), not from ensure; an ensure clause is for side effects.

Use ensure for cleanup that must happen: closing a file, releasing a lock, restoring a setting. In practice you rarely write it for files, because File.open("x") { |f| ... } with a block closes the file for you, but you will write it for your own resources.

Ruby ensure runs even when the error escapes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The order is start, working, end job, and only then the outer rescue prints. The exception passes through with_log, which cleans up on the way out.

Raising exceptions

Use raise to signal a problem. Its forms:

  • raise "text" raises a RuntimeError with that message;
  • raise ArgumentError raises that class with its default message (the class name);
  • raise ArgumentError, "age must be positive" is the usual form;
  • raise error_object re-raises an existing exception, and a bare raise inside a rescue clause re-raises the current one.
Ruby Raising and re-raising

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Choose the class that tells the caller what kind of problem it is: ArgumentError for bad arguments, TypeError for the wrong type, KeyError for a missing key, NotImplementedError for an abstract method, RuntimeError (the default) for anything unusual. Write messages that include the offending value, as above; a message like invalid costs the next reader an hour.

retry

Inside a rescue clause, retry jumps back to the top of the begin block. It is the natural tool for flaky operations such as network calls. Always bound the number of attempts, or you write an infinite loop.

Ruby Retrying with a limit

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

In real code you would also sleep between attempts, with a delay that grows each time (exponential backoff), and only retry errors that are likely to be temporary.

The rescue modifier and why to avoid it

Ruby allows expression rescue fallback on one line:

Ruby The rescue modifier

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

It rescues StandardError only, with no way to name the class, so it also swallows typos and unrelated bugs. A misspelled method name raises NoMethodError, and the modifier hides it. Prefer Integer("oops", exception: false), which returns nil instead of raising, or a proper rescue ArgumentError.

cause, backtraces and full_message

When you raise a new exception inside a rescue clause, Ruby remembers the original in cause. This lets you translate low-level failures into domain errors without losing the story.

Ruby cause and full_message

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

full_message(highlight: false) returns the text Ruby would print for an uncaught exception, without color codes, including the chain of causes. It is what you want in a log. Use raise ... , cause: other to set the cause explicitly, or cause: nil to hide it.

Habits worth keeping

  • Rescue narrowly. Name the exception classes you expect and let the rest crash loudly.
  • Do not swallow errors. An empty rescue; end turns a bug into a mystery. At minimum log the exception.
  • Do not use exceptions for ordinary flow. A missing hash key is normal; use hash[:key] or fetch with a default and keep raise for genuinely exceptional states.
  • Keep the begin block small. The more code inside, the more things the rescue may accidentally catch.
  • Clean up in ensure, not in the happy path only.

For non-local jumps that are not errors, see catch and throw.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a bare rescue clause (no class given) catch?

    A bare rescue is the same as rescue StandardError. Exceptions outside that branch, such as SystemExit and Interrupt, pass through.
  2. 2. In begin/rescue/else/ensure, when does the else clause run?

    else is the success branch. ensure is the one that always runs.
  3. 3. Why is rescue Exception considered a bad idea?

    Exception is the root class. Catching it intercepts signals and exit requests that your code should normally let through.
  4. 4. What does retry do inside a rescue clause?

    retry restarts the begin block. Always cap the number of attempts so a permanent failure cannot loop forever.
  5. 5. What is the main problem with value = risky_call rescue 0?

    The modifier rescues every StandardError. That makes unrelated bugs look like the fallback value.

Summary

  • An uncaught exception stops the program and prints the file, line, method, message and class; read it from the left.
  • begin/rescue => e catches an exception object; a def or do block can hold rescue directly.
  • Clauses are checked in order, so list specific classes first. A bare rescue means StandardError; never rescue Exception.
  • else runs on success, ensure always runs, which makes it the place for cleanup.
  • raise Class, "message" signals a problem; a bare raise in a rescue re-raises; retry repeats the block and needs a limit.
  • Prefer narrow rescues and informative messages over the rescue modifier, and use cause and full_message to keep the full story.

Next: Custom Exceptions