Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →
instance method
Exception#backtrace
() -> ::Array[::String]?
backtrace → array or nil
error.c
View on GitHub ↗
static VALUE
exc_backtrace(VALUE exc)
{
VALUE obj;
obj = rb_attr_get(exc, id_bt);
if (rb_backtrace_p(obj)) {
obj = rb_backtrace_to_str_ary(obj);
/* rb_ivar_set(exc, id_bt, obj); */
}
return obj;
}
Returns the backtrace (the list of code locations that led to the exception), as an array of strings.
Example (assuming the code is stored in the file named t.rb):
Example
def division(numerator, denominator) numerator / denominator end begin division(1, 0) rescue => ex p ex.backtrace # ["t.rb:2:in 'Integer#/'", "t.rb:2:in 'Object#division'", "t.rb:6:in '<main>'"] loc = ex.backtrace.first p loc.class # String end
The value returned by this method migth be adjusted when raising (see Kernel#raise), or during intermediate handling by set_backtrace.
See also backtrace_locations that provide the same value, as structured objects. (Note though that two values might not be consistent with each other when backtraces are manually adjusted.)
see Backtraces.