If I run the following test, it fails:
public class CrazyExceptions {
private Exception exception;
@Before
public void setUp(){
exception = new Exception();
}
@Test
public void stackTraceMentionsTheLocationWhereTheExceptionWasThrown(){
String thisMethod = new Exception().getStackTrace()[0].getMethodName();
try {
throw exception;
}
catch(Exception e) {
assertEquals(thisMethod, e.getStackTrace()[0].getMethodName());
}
}
}
With the following error:
Expected :stackTraceMentionsTheLocationWhereTheExceptionWasThrown
Actual :setUp
The stack trace is just flat out lying.
Why isn't the stack trace rewritten when the exception is thrown? I am not a Java dev, and maybe I'm missing something here.
You wouldn't want throwing an exception to alter the stack track or you couldn't re-throw an exception safely.
The stack trace in the exception corresponds to the "new" operation, nothing else.
Because you didn't ask that that stack trace be rewritten. It was set when you created it in the setUp method, and you never did anything to alter it.
The Exception class doesn't give you any opportunity to set the method name; it's immutable. So there's no way that I know of where you could re-set the method name, unless you wanted to resort to something heinous like reflection.
Your @Test annotation doesn't tell me if you're using JUnit or TestNG, because I can't see the static import, but in either case you can run a test to see if a particular exception is thrown by using the "expected" member in the @Test annotation.
The stack trace is created when the exception is instantiated, not when it is thrown. This is specified behaviour of the Java Language Specification
I don't know why they did it that way, but if the specification defines it like that, it is at least consistent on all the various Java VMs.
However, you can refresh it by calling
exception.fillInStackTrace()
manually.Also note that you should use
Thread.currentThread().getStackTrace()
instead of usingnew Exception().getStackTrace()
(bad style).The stacktrace of the exception is filled in at creation time of the exception. Otherwise it would be impossible to catch an exception, handle it and rethrow it. The original stacktrace would get lost.
If you want to force this you have to call
exception.fillInStackTrace()
explicitly.I think the assumption is that you won't be instantiating an exception unless you are in the process of throwing it, so why pay the price to get the stack trace twice?
It would be difficult to recreate the stack trace while throwing it, as that is just sending the object out.
The exception should be fully setup before the throw, so part of the instantiation is to get the stack trace.
UPDATE:
You can call
fillInStackTrace()
to resolve this.