kann ein beliebiger ThrowableKann ein ExceptionInInitializerError abgefangen werden?
class CatchThrowable {
public static void main(String[] args){
try{
throw new Throwable();
} catch (Throwable t){
System.out.println("throwable caught!");
}
}
}
Ausgang gefangen werden:
throwable caught!
Also, wenn ich etwas Schlimmes während eines Initialisierungsbaustein tun, würde ich einen ExceptionInInitializerError fangen zu können, erwarten. Allerdings ist die folgende nicht:
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){}
}
Ausgang:
java.lang.ExceptionInInitializerError
Caused by: java.lang.ArrayIndexOutOfBoundsException: 4
at InitError.<clinit>(InitError.java:13)
Exception in thread "main"
und wenn ich den Code ändern zusätzlich eine ArrayIndexOutOfBoundsException zu fangen
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){}
}
es ist die ArrayIndexOutOfBoundsException, die gefangen wird:
ArrayIndexOutOfBoundsException caught!
Kann mir jemand sagen, warum das ist?
Der 'ExceptionInInitializerError' wird nicht in den' try' Block geworfen. Es wird von einer nicht abgefangenen Ausnahme verursacht, die aus Ihrem statischen Block geworfen wird. – khelwood