2016-08-13 82 views
2

任何Throwable的可以被捕获是否有可能捕获ExceptionInInitializerError?

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.<clinit>(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! 

有人能告诉我为什么是这样吗?

+0

'ExceptionInInitializerError'没有被抛入你的'try'块。它是由一个未被捕获的异常从你的'static'块中抛出。 – khelwood

回答

3

顾名思义,ExceptionInInitializerError是一个错误,不是一个例外。不像例外,errors are not meant to be caught。它们表示致命的不可恢复的状态,并且意味着停止您的程序。

ExceptionInInitializerError表示static变量的初始值设定项引发了一个未被捕获的异常 - 在您的情况下,它是ArrayIndexOutOfBoundsException,但是任何异常都会导致此错误。由于静态初始化发生在正在运行的程序的上下文之外,因此无法提供异常。这就是为什么Java产生错误而不是发送异常的原因。

相关问题