任何Throwable的可以被捕获是否有可能捕获ExceptionInInitializerError?
class CatchThrowable {
public static void main(String[] args){
try{
throw new Throwable();
} catch (Throwable t){
System.out.println("throwable caught!");
}
}
}
输出:
throwable caught!
所以,如果我初始化块期间做坏事,我希望能够赶上一个的ExceptionInInitializerError。但是,以下不工作:
class InitError {
static int[] x = new int[4];
static { //static init block
try{
x[4] = 5; //bad array index!
} catch (ExceptionInInitializerError e) {
System.out.println("ExceptionInInitializerError caught!");
}
}
public static void main(String[] args){}
}
输出:
java.lang.ExceptionInInitializerError
Caused by: java.lang.ArrayIndexOutOfBoundsException: 4
at InitError.<clinit>(InitError.java:13)
Exception in thread "main"
,如果我改变了代码,以另外搭上一个ArrayIndexOutOfBoundsException
class InitError {
static int[] x = new int[4];
static { //static init block
try{
x[4] = 5; //bad array index!
} catch (ExceptionInInitializerError e) {
System.out.println("ExceptionInInitializerError caught!");
} catch (ArrayIndexOutOfBoundsException e){
System.out.println("ArrayIndexOutOfBoundsException caught!");
}
}
public static void main(String[] args){}
}
那就是被抓住的ArrayIndexOutOfBoundsException异常:
ArrayIndexOutOfBoundsException caught!
有人能告诉我为什么是这样吗?
'ExceptionInInitializerError'没有被抛入你的'try'块。它是由一个未被捕获的异常从你的'static'块中抛出。 – khelwood