Exception object carries information about an exception:
Its type (the exception's class).
An optional descriptive message.
Optional backtrace information.
Two Ruby statements have default exception classes:
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
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
Equality—If obj is not an
false. Otherwise, returns
true if exc and obj share same class, messages, and backtrace.
Returns any backtrace associated with the exception. The backtrace is an array of strings, each containing either “filename:lineNo: in `method''' or “filename:lineNo.''
def a raise "boom" end def b a() end begin b() rescue => detail print detail.backtrace.join("\n") end
prog.rb:2:in `a' prog.rb:6:in `b' prog.rb:10
In the case no backtrace has been set,
nil is returned
ex = StandardError.new ex.backtrace #=> nil
Returns the previous exception ($!) at the time this exception was raised. This is useful for wrapping exceptions and retaining the original exception information.
With no argument, or if the argument is the same as the receiver, return the receiver. Otherwise, create a new exception object of the same class as the receiver, but with a message equal to
Returns formatted string of exception. The returned string is formatted using the same format that Ruby uses when printing an uncaught exceptions to stderr.
If highlight is
true the default error handler will send the messages to a tty.
order must be either of
:bottom, and places the error message and the innermost backtrace come at the top or the bottom.
The default values of these options depend on
$stderr and its
tty? at the timing of a call.
Returns the result of invoking
exception.to_s. Normally this returns the exception's message or name.
Construct a new
Exception object, optionally passing in a message.
Returns exception's message (or the name of the exception if no message is set).