This blog is part of our Ruby 2.5 series.
Stack trace or backtrace is a sequential representation of the stack of method calls in a program which gets printed when an exception is raised. It is often used to find out the exact location in a program from where the exception was raised.
Before Ruby 2.5
Before Ruby 2.5, the printed backtrace contained the exception class and the error message at the top. Next line contained where in the program the exception was raised. Next we got more lines which contained cascaded method calls.
Consider a simple Ruby program.
Let’s execute it using Ruby 2.4.
In the printed backtrace above, the first line shows the location, error message and the exception class name; whereas the subsequent lines shows the caller method names and their locations. Each line in the backtrace above is often considered as a stack frame placed on the call stack.
Most of the times, a backtrace has so many lines that it makes it very difficult to fit the whole backtrace in the visible viewport of the terminal.
Since the backtrace is printed in top to bottom order the meaningful information like error message, exception class and the exact location where the exception was raised is displayed at top of the backtrace. It means developers often need to scroll to the top in the terminal window to find out what went wrong.
After Ruby 2.5
Over 4 years ago an issue was created to make printing of backtrace in reverse order configurable.
After much discussion
made the commit to
print backtrace and error message
in reverse order
only when the error output device (
is a TTY (i.e. a terminal).
Message will not be printed in reverse order
if the original
is attached to something like a
Look at the code here
where the check happens
STDERR is a TTY
and is unchanged.
Let’s execute the same program using Ruby 2.5.
We can notice two new changes in the above backtrace.
- The error message and exception class is printed last (i.e. at the bottom).
- The stack also adds frame number when printing in reverse order.
This feature makes the debugging convenient when the backtrace size is a quite big and cannot fit in the terminal window. We can easily see the error message without scrolling up now.
still holds an array of stack frames
in the top to bottom order.
So if we rescue the caught exception and print the backtrace manually
we will get the old behavior.
note that if we assign
STDERR with a
thus making it a non-TTY
we can get the old behavior
but the backtrace would be written
to the specified file
and not to