Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 134 ยท Control Flow

Custom Exceptions

Learn to write custom exception classes in Ruby - subclassing StandardError, error hierarchies, extra data, default messages, cause, exit codes and best practices.

Ruby's built-in exceptions describe technical failures: ZeroDivisionError, KeyError, IOError. Your program has its own failures: "insufficient funds", "order already shipped", "invalid coupon". If you raise RuntimeError with a message for all of them, callers can only tell them apart by parsing text, which is fragile. A custom exception class gives each failure a name, lets callers rescue exactly what they care about, and can carry data such as the account or the missing amount.

Writing one takes a single line. This lesson covers that line, how to build a small hierarchy for a library or application, how to add data and good default messages, how cause preserves the original failure, and how to turn exceptions into exit codes. It builds on Exceptions.

The smallest custom exception

Subclass StandardError (not Exception), so that a plain rescue still catches your error.

Ruby A one-line exception class

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.

class InsufficientFunds < StandardError; end creates a class with everything an exception needs: message, backtrace, cause, and raise support. The name should describe the problem, not the code that raises it, and by convention it does not end in Error when the noun already says it (InsufficientFunds, Timeout::Error), though many libraries do use the suffix (ParseError, ConnectionError). Pick one style and stay with it.

If you forget to rescue it, Ruby treats it like any other uncaught exception.

Ruby An unhandled custom 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 program stops with main.rb:4:in 'Object#withdraw': balance 100, requested 250 (InsufficientFunds) and a backtrace. Your class name appears in parentheses, which is exactly why a dedicated class beats a generic message.

A hierarchy for your library

Real libraries define one base class and derive specific errors from it. Callers can then rescue the whole family, or one member.

Ruby A base error and specific subclasses

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.

OutOfStock is handled specially. Any other Shop::Error hits the second clause, and everything else (such as the ArgumentError, a bug in the caller) goes to the last. The module Shop acts as a namespace (Modules and Mixins explains this), so users of your code write rescue Shop::Error and are protected from new subclasses you add later.

Design tips for a hierarchy:

  • One root per library (MyLib::Error) so callers can rescue "anything from this library".
  • Group by what the caller can do about it, not by where in your code it came from. "Retry later" and "fix your input" deserve different branches.
  • Keep it shallow. Two or three levels are almost always enough.
  • Do not subclass Exception directly unless you really want the error to bypass a plain rescue.

Carrying data

An exception is an object, so it can have attributes. Define initialize, call super with the message, and store the extra values.

Ruby An exception with extra data

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 caller now gets structured data, not just text. It could show a "top up by 60" button using e.shortfall. Note raise InsufficientFunds.new(...): when your initialize takes custom arguments, build the object yourself and pass it to raise. Calling super with a string sets the message.

If you override initialize and forget to call super, e.message falls back to the class name. Always pass a message to super, or override message itself.

Default messages

Often an error should work without a message. Give initialize a default:

Ruby A default 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.

A bare super inside initialize passes along the same arguments the method received, including the default. The third block shows p e, which prints the inspect form: the class name followed by the message in angle brackets. Without a default, raise ValidationError would produce a message equal to the class name.

Wrapping errors with cause

When code at one level fails because a lower level failed, raise your own error from inside the rescue. Ruby links the old one automatically as cause, so no information is lost.

Ruby Translating a low-level error

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 settings hash prints 8080; the other two print a ConfigError message plus the original class, KeyError or ArgumentError. Upper layers deal with a stable, meaningful class while debugging tools still see the underlying cause. This is the usual way to hide implementation details (a database driver's error, an HTTP client's timeout) behind your own API.

Exceptions and exit codes

A script that fails should tell its caller (a shell, a CI job) with a non-zero exit code. An uncaught exception already gives exit code 1. For finer control, rescue at the top of your script and call exit, which itself works by raising SystemExit.

Ruby Mapping errors to exit codes

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 a real script the last line is exit(main(ARGV)). Keeping main as an ordinary method that returns the code makes it testable: tests call main and check the number, without the process actually exiting. warn writes to standard error, which is where error messages belong.

Checking your own hierarchy

Because the classes are ordinary, you can inspect them:

Ruby Inspecting exception classes

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.

Class#subclasses lists direct subclasses, handy for documentation or tests that make sure every error maps to an exit code or an HTTP status.

Best practices

  • Subclass StandardError, with one base class per library.
  • Name the class after the problem. Put information in the message, such as the offending value, not in the class name.
  • Offer data as attributes when callers might act on it, and keep a readable message.
  • Do not create a class for every raise. If nobody will ever rescue it separately, ArgumentError or RuntimeError with a good message is enough.
  • Rescue your base class at layer boundaries and re-raise as a higher-level error, keeping the cause.
  • Never use exceptions for expected, frequent outcomes: validating user input usually returns a list of errors rather than raising.

For jumping out of deeply nested code without an error, see catch and throw.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which line defines a custom exception that a plain rescue will catch?

    A plain rescue catches StandardError and its subclasses. A class that does not inherit from an exception class cannot be raised at all.
  2. 2. Why do libraries usually define a base error class such as MyLib::Error?

    A shared root lets callers choose between rescuing one specific error and rescuing the whole family.
  3. 3. You override initialize in an exception class and never call super. What is likely to happen to e.message?

    Without super the message is never set, so Ruby uses the class name as the message.
  4. 4. What does cause contain when you raise a new exception inside a rescue clause?

    Ruby sets cause automatically to the exception currently being rescued, so the original failure stays available.
  5. 5. Which is the better use of a custom exception?

    Exceptions suit exceptional conditions a caller may want to handle by type. Frequent, expected outcomes are better modeled with return values.

Summary

  • Define an error with class MyError < StandardError; end; never subclass Exception for ordinary errors.
  • Use one base class per library and a shallow hierarchy so callers can rescue broadly or narrowly.
  • Add attributes and call super with a message, or give initialize a default message.
  • Raising inside a rescue keeps the original error as cause.
  • Rescue at the edge of a script, print to warn, and return meaningful exit codes.

Next: catch and throw