是否可以捕获ExceptionInInitializerError?
任何Throwable都可以被捕获
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.(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
是一个错误,而不是exception。 与exception不同, 错误并不意味着被捕获 。 它们表示致命的不可恢复的状态,并且意味着停止您的计划。
ExceptionInInitializerError
指示static
变量的初始化器抛出了一个尚未捕获的exception – 在您的情况下,它是ArrayIndexOutOfBoundsException
,但任何exception都将导致此错误。 由于静态初始化发生在正在运行的程序的上下文之外,因此无法传递exception。 这就是Java产生错误而不是传递exception的原因。