Skip to Content

I rarely found a use of Throwable.fillInStackTrace()… until recently. I had to delegate some coding into a different Thread (for the specialists: I had to do some UI stuff in SWT from a non-UI thread; there is a hook in SWT to have some coding running in the UI thread). Since it was coding designated for testing, Exceptions could happen. Therefore I caught them and rethrew them in the initiating thread. However the stacktrace, since run in another thread was not very informative and did not tell about the location which now was throwing the exception. The first option was to throw a new Exception and to add the caught one as the cause. Alternatively I experimented with Throwable.fillInStackTrace(), expecting that this just would add the actual stack frame to the trace. But I was very astonished in finding that the previous stack trace (from the delegated thread) was erased completely and the entire call stack of the calling thread was filled in. I wrote the following test code to make myself familiar with the behavior:

When running the test the outcome is something like:

The first trace shows the stack trace of the runnable where the exception has been generated. The second and third one the stack trace of the originating thread. As a result, in cases where the trace of the originating thread is more interesting for tracing the fault, this can be a possibility how to track it. This is especially important in environments like JUnit, that when an error or failure occurs one wishes to know at which point of the test coding the test failed. That information is not present when simply rethrowing an exception originating from a delegated thread.

To report this post you need to login first.

Be the first to leave a comment

You must be Logged on to comment or reply to a post.

Leave a Reply