Class Exception and its subclasses are used to communicate between
rescue statements in
begin ... end blocks.
An Exception object carries information about an exception:
- Its type (the exception’s class).
- An optional descriptive message.
- Optional backtrace information.
Some built-in subclasses of Exception have additional methods: e.g.,
Two Ruby statements have default exception classes:
raise: defaults to RuntimeError.
rescue: defaults to StandardError.
When an exception has been raised but not yet handled (in
END blocks), two global variables are set:
$!contains the current exception.
$@contains its backtrace.
To provide additional or alternate information, a program may create custom exception classes that derive from the built-in exception classes.
A good practice is for a library to create a single “generic” exception class (typically a subclass of StandardError or RuntimeError) and have its other exception classes derive from that class. This allows the user to rescue the generic exception, thus catching all exceptions the library may raise even if future versions of the library add new exception subclasses.
class MyLibrary class Error < ::StandardError end class WidgetError < Error end class FrobError < Error end end
To handle both MyLibrary::WidgetError and MyLibrary::FrobError the library user can rescue MyLibrary::Error.
The built-in subclasses of Exception are: