liveBook · Manning

Stack trace

As explained in The Well-Grounded Rubyist, Fourth Edition

Stack tracing is the technique of examining the sequence of active calls during program execution.

A stack trace records the active method-call sequence at a point during Ruby execution. It identifies the files, line numbers, and methods that led to an error or to the current location, making it useful for debugging. section 1.3.3 section 15.4.1

Reading an exception backtrace

An exception object exposes its call history through backtrace. For a rescued ArgumentError, entries such as fussy.rb:2:in 'fussy_method' and fussy.rb:6:in '<main>' show where the exception arose and how execution reached it. The same exception object also provides its message. section 6.4.6

Ruby exposes stack information both automatically in error output and explicitly through caller. caller returns strings ordered from the most recent call backward; caller_locations provides a parsed interface for examining stack frames. section 15.4.1 section 15.6

Tracing nested calls

If x calls y and y calls z, calling caller inside z reports y first, then x, then <main>. Replacing caller with raise produces the familiar fatal-error format, including the current frame and the calls that led there.

def x
  y
end
def y
  z
end
def z
  puts "Stacktrace: "
  p caller
end
x

Browse the minimal x-to-y-to-z program used to generate a stack trace with caller. section 15.4.1

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains call ordering, exception backtraces, caller output, and caller_locations, but does not detail the parsed location interface.
Examples
Uses URI loading errors, rescued ArgumentError output, nested x-y-z calls, and a raised exception to demonstrate trace formats.
What it assumes
Assumes familiarity with Ruby method calls and exceptions while demonstrating exception capture and stack inspection directly.
What you can do after
Diagnose/debug with it by reading automatic traces, printing exception backtraces, and inspecting caller-generated call histories.
How it connects
Connects exceptions, rescue clauses, debugging, runtime introspection, and method calls.

Also explained in

Compare how 7 books explain stack trace →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.