Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

instance method

Exception#backtrace_locations

() -> ::Array[::Thread::Backtrace::Location]?
backtrace_locations → array or nil

Returns the backtrace (the list of code locations that led to the exception), as an array of Thread::Backtrace::Location instances.

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_locations
  # ["t.rb:2:in 'Integer#/'", "t.rb:2:in 'Object#division'", "t.rb:6:in '<main>'"]
  loc = ex.backtrace_locations.first
  p loc.class
  # Thread::Backtrace::Location
  p loc.path
  # "t.rb"
  p loc.lineno
  # 2
  p loc.label
  # "Integer#/"
end

The value returned by this method might be adjusted when raising (see Kernel#raise), or during intermediate handling by set_backtrace.

See also backtrace that provide the same value as an array of strings. (Note though that two values might not be consistent with each other when backtraces are manually adjusted.)

See Backtraces.

See also #backtrace #cause #== #detailed_message also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0