6

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?

twisted
  • 742
  • 2
  • 11
  • 19
  • The `ExceptionInInitializerError` isn't being thrown inside your `try` block. It is caused by an uncaught exception being thrown out of your `static` block. – khelwood Aug 13 '16 at 10:49
  • `catch (Throwable t) {}` can catch the error. because `ExceptionInInitializerError` is an Error that extends Throwable. – SHRIN Apr 04 '23 at 05:39

1 Answers1

6

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.

Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523