Given this program:
class Test {
public static void main(String[] args) {
try {
throw new NullPointerException();
} catch (NullPointerException npe) {
System.out.println("In catch");
} finally {
System.out.println("In finally");
}
}
}
Sun's javac
(v 1.6.0_24) produces the following bytecode:
public static void main(java.lang.String[]);
// Instantiate / throw NPE
0: new #2; // class NullPointerException
3: dup
4: invokespecial #3; // Method NullPointerException."<init>":()V
7: athrow
// Start of catch clause
8: astore_1
9: getstatic #4; // Field System.out
12: ldc #5; // "In catch"
14: invokevirtual #6; // Method PrintStream.println
17: getstatic #4; // Field System.out
// Inlined finally block
20: ldc #7; // String In finally
22: invokevirtual #6; // Method PrintStream.println
25: goto 39
// Finally block
// store "incomming" exception(?)
28: astore_2
29: getstatic #4; // Field System.out
32: ldc #7; // "In finally"
34: invokevirtual #6; // Method PrintStream.println
// rethrow "incomming" exception
37: aload_2
38: athrow
39: return
With the following exception table:
Exception table:
from to target type
0 8 8 Class NullPointerException
0 17 28 any
28 29 28 any
My question is: Why on earth does it include that last entry in the exception table?!
As I understand it, it basically says "if the astore_2
throws an exception, catch it, and retry the same instruction".
Such entry is produced even with empty try / catch / finally clauses such as
try {} catch (NullPointerException npe) {} finally {}
Some observations
- Eclipse compiler does not produce any such exception table entry
- The JVM spec does not document any runtime exceptions for the
astore
instruction. - I know that it is legal for the JVM to throw
VirtualMachineError
for any instruction. I guess the peculiar entry prevents any such errors from propagating out from that instruction.