rgh rgh - 3 months ago 28
Java Question

Is it possible to catch an ExceptionInInitializerError?

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?

Answer

As its name implies, ExceptionInInitializerError is an error, not an exception. Unlike exceptions, errors are not meant to be caught. They indicate fatal unrecoverable states, and are meant to stop your program.

ExceptionInInitializerError indicates that an initializer of a static variable threw an exception that has not been caught - in your case, it's ArrayIndexOutOfBoundsException, but any exception will cause this error. Since static initialization happens outside the context of your running program, there is no place to deliver the exception. That is why Java produces an error rather than delivering an exception.