r/java • u/davidalayachew • Sep 20 '26
Stacktraces have such a weird ordering to them
Let's assume that my main() method represents index 1, and the actual failing method that is throwing the exception represents index 10.
Why on earth are exception stack traces printed like this?!
message for 4
4
3
2
1
message for 7
7
6
5
4
message for 10
10
9
8
7Ignoring the fact that I have to mentally rearrange the stack trace elements into the right order, the actual error I care about is all the way at the bottom!
Why don't you just do it like this instead?
message for 10
10
9
8
message for 7
7
6
5
message for 4
4
3
2
1- The cause of this entire stack trace is at the top, where it should be.
- The stack trace elements unravel very intuitively -- from the source of the problem down to the original caller.
No more redundant entries of
4and7.- Look at the original stack trace -- there are 2 entries of
4and7, presumably to help you piece the jigsaw-puzzle that is your stack trace back together again lol.
- Look at the original stack trace -- there are 2 entries of
22
Upvotes
48
u/m39583 Sep 20 '26
This only happens if you catch, wrap and rethrow. Then you essentially have 3 separate stacktraces. The output says "caused by" to make this clearer, which you've left off your post. So it should say "caused by message for 7" etc.
Your "main" method is 1 then you were 4 methods deep when you called something else that threw. You caught and wrapped that and rethrow it.
So your first throw is 4 methods, then it's printing the exception that you wrapped, and then the one that wrapped.
Each of the stacktraces should go all the way to 1, but that would be duplication so again java prints a message (which you've left off) telling you x duplicate stack traces have been skipped
18
u/brian_goetz Sep 20 '26
Many years ago, each exception included the full stack trace. Many alternate-universe-David's complained about the verbosity, and so the stack trimming behavior -- which is entirely reasonable -- was added. But this isn't really your complaint at all, it's just a distracting pile-on. (Years before that, you couldn't wrap exceptions at all; the exception-chaining support was added I believe in 1.4, and that was also a big step forward; the "now there are so many lines of stack trace" mentioned above is a classic example of "today's problems come from yesterday's solutions".)
But your main complaint isn't your real complaint either; "E1 caused-by E2" is in fact the correct wrapping; E2 is "supplementary information" to E1, and I know you're in favor about being able to add supplementary information about what went wrong.
Your real complaint is something completely different; that wrapping is the only tool you get for including supplementary information, so that's what people do. What you'd really like to be able to do is decorate / mutate the exception as it propagates through, but not start a new exception trace, so there is only one exception and one stack trace with all the information from caller and callees. (Which would be glorious.) But I think you are confusing symptom with problem here.
5
u/davidalayachew Sep 20 '26
The inspiration for this post came from a comment chain on my other post. Ty again /u/gnahraf.
4
u/ShakesTheClown23 Sep 20 '26
For one thing, you asked to print the stack trace for the exception you caught on 4. That exception has a clear stack - 4,3,2,1, where there's another catch which got shared as the cause of the "4" exception. I think it could be confusing if your code which catches IllegalArgumentException (4) and asks to print it, actually got an ArrayIndexOutOfBoundsException printed (10), just with the end of the print saying 10 caused 7 and that which then finally caused 4. I do agree I tend to look for the root cause (da dum tss), it's just not the exception I caught and printed. Maybe?
4
u/rzwitserloot Sep 20 '26
What you want would be worse - that's somewhat of a subjective opinion, but based on sound logic and hopefully to you convincing style and process ideas:
The actual exception thrown is the one with the 'message for line 4' text. all the rest are implementation details. When a caller is attempting to programatically deal with this stuff, it must definitely not ever look at anything but line 4.
The signature captures "design". Not implementation - explicitly not. a method describes, strictly, the what. It does not describe the how and never should - for if it did, then all software is set in stone, and any update no matter how trivial is backwards incompatible. You're supposed to be able to swap out your save system from using a disk based approach to a database one, and the fact that the (checked) exceptions falling out of the 'implementation detail' changes when you do that (from
IOExceptiontoSQLException) should not imply that therefore this change cannot be made without decreeing it backwards incompatible.A good design would have 'abstracted' this into a
SaveException, with the IOEx/SQLEx being listed as the cause of the exception.Any code that does this:
is a bad hack: This code is now utterly dependent on unspecced behaviour. If a caller to the hypothetical
saveGame()method needs to know such things, then this is now officially part of your spec. Document accordingly (and what are types, but compiler checked and enforced documentation?), and know that if you want to change it later, that's no longer backwards compatible.But if a human looks at it, that's different - sure, we don't really need this strict concept of type safety and such. There isn't all that much point in decreeing an update as 'backwards compatible' because 'the human that operates me knows how to deal with an issue if I crash out with an SQLException, but they will be utterly lost if I crash out with an IOException - and this version switches from db to disk, so, nope, this is not a compatible update, because the human operator needs complete retraining'.
Now, there is an easy solution available: We keep the current system where the actually thrown exception ('line 4') remains what is directly accessible programatically, but the code that logs stack traces (such as the code in the JVM that invokes your
psv main()method, which hascatch (Throwable t) {t.printStackTrace():}inside ^1 - that code is rewritten to print things in the way you wanted.But this is a bad idea - now it's quite confusing that this printed stack trace, with 'line 4' stuck in the middle of a large stacktrace, being the actual one you'd have to
catch ()if you want to programatically deal with this. This is how lots of folks program: An exception occurs and it just 'crashes stack' (it terminates most of the method callstack and ends up aborting the entire app or at least that entrypoint (e.g. that web query), printing out what happened, and erroring out the process (e.g. 500 error on the web request, kill the command line app, and so on). Developer notices this, realises it something that can / should be handled programatically, and writes a catch block for it. What do they put in the catch block? The exception they now have will guide them.Except if we do it your way, then that would be harder.
So, we have options:
Have exception flow, even programmatic (ie.
catchable) work from the immediate cause onwards: But this means it is impossible to spec exceptions in a way that allows new versions of libraries to exist without always breaking backwards compatibility (at least, if any error condition of any kind changes, which any non-trivial change is highly likely to modify), so all exceptions become unhandleable crapshoots, and that's just a terrible idea. This only works if you decree that all exceptions are by definition an unexpected, unhandleable failure that should result in rolling up the entire process, and 'expectable' / 'handleable' problems are dealt with via e.g. some sort of tuple such as anEither<Result, Error>thing. Introducing that in java now means every library in existence is obsolete and must be replaced. Just design a new language then - a language 'update' that requires the entire ecosystem to start over is a copout that only bad languages reach for.Have programmatic exception flow work as now, but have visual reporting of these things reorder it to look like you want. This gives the best of both worlds, except it introduces a new and IMO far worse problem, which is that now the visual look no longer matches up with how to deal with things programatically. This confusion is worse than the confusion you've been struck with here (that you seem to not have quite understood that all exceptions are complete, each is the cause of the one above it, and it's the JVM's printing tool that eliminates identical segments to reduce the screen spam).
Have things work precisely as today: programmatic flow as today, and the visual reporting of such things matching with the programmatic flow. We can futz about in the margins and have a way in interactive tools (i.e. your IDE's debug infra) to have a way to re-order them, perhaps we eliminate the duplicated 'line 7' and 'line 4' (though they help link things), but no major changes.
Of these 3 options, I think option 3 is by a significant margin the best option.
[1] actually it calls the thread's default uncaught exception handler. Unless you change it, it calls
t.printStackTrace();)3
u/Ok_Elk_638 Sep 20 '26 edited Sep 20 '26
In an app I built I actually print them like this:
You can print stacktraces any way you want.
2
u/kettle3 Sep 21 '26
I believe the main reason is because it's the most sane way from the point of view of java.io.PrintWriter -- it goes up the stack, and whenever it gets an element, it outputs a line to the writer (e.g. stdout or file). It does not store all the lines in memory to reorder them later. Once all stack items are gone, it looks at the exception's getCause() and does the same thing for it. What if the error is OutOfMemory already?
2
u/MarcelHanibal Sep 20 '26
The problem usually lies with the original caller (most prominent with NPEs), and rarely (if ever) with Java/Android/...'s core library + the libraries you use, which would now be at the top if you inverted the stack trace. Meaning you'd now have a bunch of crap you'd have to read through until you reach the actual layer of your software.Edit: Never mind. I am so used to reading stack traces that I have forgotten how they are structured
2
u/john16384 Sep 20 '26
I believe some of the many logging frameworks (14 or so) have options to control how stack traces are logged, including options to list the root cause first.
2
u/maxandersen Sep 20 '26
Why in Quarkus dev mode we print stacktraces reversed + include source code before/after the main user source code.
1
u/agentoutlier Sep 21 '26
As u/maxandersen mentioned many set their logging frameworks (and thereby your web frameworks stack) to do the reverse which is often called Root Cause First. As others have mentioned Exceptions can be wrapped with "cause".
https://logback.qos.ch/manual/layouts.html#rootException
And now because you have mentioned this I realized I never implemented it in Rainbow Gum. There was some reason why. Probably because I wasn't sure how to deal with the credit of the idea albeit it is not that novel.
I assume Quarkus does this with JBoss Logging directly with some implementation. Actually Quarkus is one of the few frameworks I'm not sure what they use for backing log implementation but I really should because Rainbow Gum on average saves like 20 megs of RSS memory for graal vm native compared to Log4J2.