class Exception

Practical examples and pitfalls for Exception

Exception examples: rescue at the boundary you understand

Practical notes by Ruby-Doc.org

Handle the failure that the operation can report

A conversion helper should make a deliberate choice about invalid input. In this example an invalid integer spelling becomes a short result message, and the rescue clause names the conversion error it expects. The protected operation is small enough that an unrelated failure is unlikely to be mistaken for bad input.

Example 1
def read_count(text)
  Integer(text, 10)
rescue ArgumentError
  "invalid count"
end
p read_count("18")
p read_count("eighteen")
Expected output
18
"invalid count"

That message is a demonstration interface. A real caller may need a structured result or an exception of its own. What matters is that a failed conversion does not silently become a plausible count, and that the caller can tell success from failure without guessing from a default number.

Translate an error without losing its cause

At a boundary between a parsing detail and an application operation, a named exception can explain what the caller was trying to do. Raising it while handling the original error retains the original exception as its cause. This gives a higher-level message while keeping the underlying failure available for diagnosis.

Example 2
class CountError < StandardError; end
def parse_count(text)
  Integer(text, 10)
rescue ArgumentError
  raise CountError, "cannot read shipment count"
end
begin
  parse_count("many")
rescue CountError => error
  puts error.message
  puts error.cause.class
end
Expected output
cannot read shipment count
ArgumentError

Use a custom type when callers need to distinguish this failure from other operations. Avoid translating every exception into the same generic type: that can erase distinctions the caller needs to decide whether to retry, correct the input or stop.

Keep cleanup separate from recovery

An ensure clause is for work that must happen when leaving the protected body, such as releasing a resource. It does not mean the operation succeeded. A block form of a resource-opening API is often easier to use because it already provides the cleanup behavior.

Ordinary application exceptions usually inherit from StandardError; a bare rescue handles that family. Rescuing Exception also reaches conditions such as process-exit requests that most application recovery code should leave alone. Keep rescue clauses as narrow as the recovery decision allows, and let unexpected errors reach a place where they can be reported with their backtrace and cause.

API reference: Exception API reference

Related: StandardError · Kernel · IO

Class Exception and its subclasses are used to indicate that an error or other problem has occurred, and may need to be handled. See Exceptions.

An Exception object carries certain information:

Built-In Exception Class Hierarchy

The hierarchy of built-in subclasses of class Exception: