Exception: Exception
Overview
Descendants of class Exception are used to communicate between Kernel#raise and rescue
statements in begin ... end
blocks. Exception objects carry information about the exception – its type (the exception’s class name), an optional descriptive string, and optional traceback information. Exception subclasses may add additional information like NameError#name.
Programs may make subclasses of Exception, typically of StandardError or RuntimeError, to provide custom classes and add additional information. See the subclass list below for defaults for raise
and rescue
.
When an exception has been raised but not yet handled (in rescue
, ensure
, at_exit
and END
blocks) the global variable $!
will contain the current exception and $@
contains the current exception’s backtrace.
It is recommended that a library should have one subclass of StandardError or RuntimeError and have specific exception types inherit from it. This allows the user to rescue a generic exception type to catch all exceptions the library may raise even if future versions of the library add new exception subclasses.
For example:
class MyLibrary
class Error < RuntimeError
end
class WidgetError < Error
end
class FrobError < Error
end
end
To handle both WidgetError and FrobError the library user can rescue MyLibrary::Error.
The built-in subclasses of Exception are:
-
NoMemoryError
-
ScriptError
-
LoadError
-
NotImplementedError
-
SyntaxError
-
-
SecurityError
-
SignalException
-
Interrupt
-
-
StandardError – default for
rescue
-
ArgumentError
-
UncaughtThrowError
-
-
EncodingError
-
FiberError
-
IOError
-
EOFError
-
-
IndexError
-
KeyError
-
StopIteration
-
-
LocalJumpError
-
NameError
-
NoMethodError
-
-
RangeError
-
FloatDomainError
-
-
RegexpError
-
RuntimeError – default for
raise
-
SystemCallError
-
Errno::*
-
-
ThreadError
-
TypeError
-
ZeroDivisionError
-
-
SystemExit
-
SystemStackError
-
fatal – impossible to rescue
Direct Known Subclasses
NoMemoryError, ScriptError, SecurityError, SignalException, StandardError, SystemExit, SystemStackError, fatal
Class Method Summary collapse
-
.exception ⇒ Object
call-seq: exc.exception(string) -> an_exception or exc.
Instance Method Summary collapse
-
#==(obj) ⇒ Boolean
Equality—If obj is not an
Exception
, returnsfalse
. -
#backtrace ⇒ Array
Returns any backtrace associated with the exception.
-
#backtrace_locations ⇒ Array
Returns any backtrace associated with the exception.
-
#cause ⇒ Exception?
Returns the previous exception ($!) at the time this exception was raised.
-
#exception(*args) ⇒ Object
call-seq: exc.exception(string) -> an_exception or exc.
-
#new(msg = nil) ⇒ Exception
constructor
Construct a new Exception object, optionally passing in a message.
-
#inspect ⇒ String
Return this exception’s class name and message.
-
#message ⇒ String
Returns the result of invoking
exception.to_s
. -
#set_backtrace(backtrace) ⇒ Array
Sets the backtrace information associated with
exc
. -
#to_s ⇒ String
Returns exception’s message (or the name of the exception if no message is set).
Constructor Details
#new(msg = nil) ⇒ Exception
Construct a new Exception object, optionally passing in
a message.
677 678 679 680 681 682 683 684 685 686 687 |
# File 'error.c', line 677
static VALUE
exc_initialize(int argc, VALUE *argv, VALUE exc)
{
VALUE arg;
rb_scan_args(argc, argv, "01", &arg);
rb_iv_set(exc, "mesg", arg);
rb_iv_set(exc, "bt", Qnil);
return exc;
}
|
Class Method Details
.exception ⇒ Object
call-seq:
exc.exception(string) -> an_exception or exc
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 string.to_str
.
Instance Method Details
#==(obj) ⇒ Boolean
Equality—If obj is not an Exception
, returns false
. Otherwise, returns true
if exc and obj share same class, messages, and backtrace.
922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 |
# File 'error.c', line 922
static VALUE
exc_equal(VALUE exc, VALUE obj)
{
VALUE mesg, backtrace;
const ID id_mesg = idMesg;
if (exc == obj) return Qtrue;
if (rb_obj_class(exc) != rb_obj_class(obj)) {
int status = 0;
ID id_message, id_backtrace;
CONST_ID(id_message, "message");
CONST_ID(id_backtrace, "backtrace");
obj = rb_protect(try_convert_to_exception, obj, &status);
if (status || obj == Qundef) {
rb_set_errinfo(Qnil);
return Qfalse;
}
if (rb_obj_class(exc) != rb_obj_class(obj)) return Qfalse;
mesg = rb_check_funcall(obj, id_message, 0, 0);
if (mesg == Qundef) return Qfalse;
backtrace = rb_check_funcall(obj, id_backtrace, 0, 0);
if (backtrace == Qundef) return Qfalse;
}
else {
mesg = rb_attr_get(obj, id_mesg);
backtrace = exc_backtrace(obj);
}
if (!rb_equal(rb_attr_get(exc, id_mesg), mesg))
return Qfalse;
if (!rb_equal(exc_backtrace(exc), backtrace))
return Qfalse;
return Qtrue;
}
|
#backtrace ⇒ Array
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
produces:
prog.rb:2:in `a'
prog.rb:6:in `b'
prog.rb:10
805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 |
# File 'error.c', line 805
static VALUE
exc_backtrace(VALUE exc)
{
ID bt;
VALUE obj;
CONST_ID(bt, "bt");
obj = rb_attr_get(exc, bt);
if (rb_backtrace_p(obj)) {
obj = rb_backtrace_to_str_ary(obj);
/* rb_iv_set(exc, "bt", obj); */
}
return obj;
}
|
#backtrace_locations ⇒ Array
Returns any backtrace associated with the exception. This method is similar to Exception#backtrace, but the backtrace is an array of
Thread::Backtrace::Location.
Now, this method is not affected by Exception#set_backtrace().
832 833 834 835 836 837 838 839 840 841 842 843 844 |
# File 'error.c', line 832
static VALUE
exc_backtrace_locations(VALUE exc)
{
ID bt_locations;
VALUE obj;
CONST_ID(bt_locations, "bt_locations");
obj = rb_attr_get(exc, bt_locations);
if (!NIL_P(obj)) {
obj = rb_backtrace_to_location_ary(obj);
}
return obj;
}
|
#cause ⇒ Exception?
Returns the previous exception ($!) at the time this exception was raised. This is useful for wrapping exceptions and retaining the original exception information.
899 900 901 902 903 904 905 |
# File 'error.c', line 899
VALUE
exc_cause(VALUE exc)
{
ID id_cause;
CONST_ID(id_cause, "cause");
return rb_attr_get(exc, id_cause);
}
|
#exception(*args) ⇒ Object
call-seq:
exc.exception(string) -> an_exception or exc
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 string.to_str
.
702 703 704 705 706 707 708 709 710 711 712 713 |
# File 'error.c', line 702
static VALUE
exc_exception(int argc, VALUE *argv, VALUE self)
{
VALUE exc;
if (argc == 0) return self;
if (argc == 1 && self == argv[0]) return self;
exc = rb_obj_clone(self);
exc_initialize(argc, argv, exc);
return exc;
}
|
#inspect ⇒ String
Return this exception’s class name and message
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 |
# File 'error.c', line 755
static VALUE
exc_inspect(VALUE exc)
{
VALUE str, klass;
klass = CLASS_OF(exc);
exc = rb_obj_as_string(exc);
if (RSTRING_LEN(exc) == 0) {
return rb_str_dup(rb_class_name(klass));
}
str = rb_str_buf_new2("#<");
klass = rb_class_name(klass);
rb_str_buf_append(str, klass);
rb_str_buf_cat(str, ": ", 2);
rb_str_buf_append(str, exc);
rb_str_buf_cat(str, ">", 1);
return str;
}
|
#message ⇒ String
Returns the result of invoking exception.to_s
. Normally this returns the exception’s message or name. By supplying a to_str method, exceptions are agreeing to be used where Strings are expected.
742 743 744 745 746 |
# File 'error.c', line 742
static VALUE
exc_message(VALUE exc)
{
return rb_funcall(exc, rb_intern("to_s"), 0, 0);
}
|
#set_backtrace(backtrace) ⇒ Array
Sets the backtrace information associated with exc
. The backtrace
must be an array of String objects or a single String in the format described in Exception#backtrace.
878 879 880 881 882 |
# File 'error.c', line 878
static VALUE
exc_set_backtrace(VALUE exc, VALUE bt)
{
return rb_iv_set(exc, "bt", rb_check_backtrace(bt));
}
|
#to_s ⇒ String
Returns exception’s message (or the name of the exception if no message is set).
723 724 725 726 727 728 729 730 |
# File 'error.c', line 723
static VALUE
exc_to_s(VALUE exc)
{
VALUE mesg = rb_attr_get(exc, rb_intern("mesg"));
if (NIL_P(mesg)) return rb_class_name(CLASS_OF(exc));
return rb_String(mesg);
}
|