I'm currently learning about exceptions in java, and wrote a test class with chained exceptions that prints the stack trace. The results, however, completely confused me about the order of execution. I've run it several times, and had gotten different outputs.
Here's the class:
public class Test {
private static void foo() {
try {
System.out.println("foo try");
bar();
} catch (Exception e) {
System.out.println("foo catch - "+e.getMessage()+", cause: "+e.getCause());
StackTraceElement elements[] = e.getStackTrace();
for (int i = 0, n = elements.length; i < n; i++) {
System.err.println(elements[i].getFileName()
+ ":" + elements[i].getLineNumber()
+ ">> "
+ elements[i].getMethodName() + "()");
}
} finally {
System.out.println("foo finally");
}
}
private static void bar() throws Exception {
try {
System.out.println("bar try");
int[] a = new int[10];
System.out.println(a[10]);
// Never reached
} catch (IndexOutOfBoundsException e) {
System.out.println("bar catch - "+e.getMessage());
throw new Exception("Chained exception", e);
} finally {
System.out.println("bar finally");
}
}
public static void main(String args[]) {
foo();
}
}
Which produced the following output for me in IntelliJ:
How can an exception be displayed before it is thrown? How can other statements be between the elements of the stack trace - in what order are they executed? As I know, the stack trace should get printed last.