考虑下面这个程序:
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的javac
(版本1.6.0_24)生成以下字节码:
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
以下是异常表:
Exception table:
from to target type
0 8 8 Class NullPointerException
0 17 28 any
28 29 28 any
我的问题是:这个异常表为什么要包括最后一个条目?!
据我所知,它基本上是在说“如果astore_2
抛出异常,则捕获它并重试相同的指令”。即使是空的try/catch/finally子句,也会生成这样的条目。
try {} catch (NullPointerException npe) {} finally {}
一些观察结果
- Eclipse编译器不会生成任何这样的异常表项。
- JVM规范没有记录
astore
指令的任何运行时异常。 - 我知道对于任何指令,JVM抛出
VirtualMachineError
都是合法的。我猜想这个奇怪的条目防止了任何这样的错误从该指令传播出来。