Any Throwable can be caught
class CatchThrowable {
public static void main(String[] args){
try{
throw new Throwable();
} catch (Throwable t){
System.out.println("throwable caught!");
}
}
}
output:
throwable caught!
So, if I do something bad during an initialization block, I'd expect to be able to catch an ExceptionInInitializerError. However, the following doesn't work:
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){}
}
output:
java.lang.ExceptionInInitializerError
Caused by: java.lang.ArrayIndexOutOfBoundsException: 4
at InitError.<clinit>(InitError.java:13)
Exception in thread "main"
and if I change the code to additionally catch an 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){}
}
it's the ArrayIndexOutOfBoundsException that gets caught:
ArrayIndexOutOfBoundsException caught!
Could anyone tell me why that is?