Java Reference
In-Depth Information
20 can be reached either by completing the TRy block normally, in which case we goto 20 at
instruction 8, or by completing the catch block and falling through from instruction 17 to
instruction 20.
The existence of the join point causes an exception during the verification of class Strange1 but not
class Strange2 . When it performs flow analysis [JLS 12.3.1] of Strange1.main , the verifier must
merge the types contained in variable 1 when instruction 20 is reached by the two different paths.
Two types are merged by computing their first common superclass [JVMS 4.9.2]. The first common
superclass of two classes is the most specific superclass they share.
The state of VM variable 1 when instruction 20 is reached from instruction 8 in Strange1.main is
that it contains an instance of the class Missing . When reached from instruction 17, it contains an
instance of the class NoClassDefFoundError . In order to compute the first common superclass, the
verifier must load the class Missing to determine its superclass. Because Missing.class has been
deleted, the verifier can't load it and throws a NoClassDefFoundError . Note that this exception is
thrown during verification, before class initialization and long before the main method begins
execution. This explains why there is no stack trace printed for the uncaught exception.
To write a program that can detect when a class is missing, use reflection to refer to the class
rather than the usual language constructs [EJ Item 35]. Here is how the program looks when
rewritten to use this technique:
public class Strange {
public static void main(String[] args) throws Exception {
try {
Object m = Class.forName("Missing").newInstance();
} catch (ClassNotFoundException ex) {
System.err.println("Got it!");
}
}
}
In summary, do not depend on catching NoClassDefFoundError . The language specification
carefully describes when class initialization occurs [JLS 12.4.1], but class loading is far less
predictable. More generally, it is rarely appropriate to catch Error or its subclasses . These
exceptions are reserved for failures from which recovery is not feasible.
 
 
Search WWH ::




Custom Search