一个 Thinking in Java 程序如下:
package typeinfo;
import static util.Print.*;
class Candy {
static { print("Loading Candy"); }
}
class Gum {
static { print("Loading Gum"); }
}
class Cookie {
static { print("Loading Cookie"); }
}
public class SweetShop {
public static void main(String[] args) {
print("inside main");
new Candy();
print("After creating Candy");
try {
Class.forName("Gum");
} catch(ClassNotFoundException e) {
print("Couldn't find Gum");
}
print("After Class.forName(\"Gum\")");
new Cookie();
print("After creating Cookie");
}
}
我期待输出如下:
/* Output:
inside main
Loading Candy
After creating Candy
Loading Gum
After Class.forName("Gum")
Loading Cookie
After creating Cookie
*/
但是得到
inside main
Loading Candy
After creating Candy
Couldn't find Gum
After Class.forName("Gum")
Loading Cookie
After creating Cookie
显然,try 块抛出了一个 ClassNotFoundException,这是出乎意料的。任何想法为什么代码抛出这个而不是初始化 Gum 类,如预期的那样?