In Java, stack traces are generated when an exception is constructed, not when it's thrown. Does anyone know what's the reasoning behind this design?
For example, in the following program, we throw an exception in method test1, but we instantiate the exception in another method, and call test1 from main. As a result, test1 never shows up in the stack trace:
class ExceptionNewVsThrow {
private static RuntimeException instantiateException() {
return new RuntimeException("Hello");
}
private static void test1(Exception exception) throws Exception {
throw exception;
}
public static void main(String[] args) throws Exception {
Exception exception = instantiateException();
test1(exception);
}
}
Exception in thread "main" java.lang.RuntimeException: Hello
at FSystem.experimental.exceptions.ExceptionNewVsThrow.instantiateException(ExceptionNewVsThrow.java:18)
at FSystem.experimental.exceptions.ExceptionNewVsThrow.main(ExceptionNewVsThrow.java:26)
See Are stack traces generated when a Java exception is thrown?