2015-08-19 90 views
1

請注意,我知道規則關於爲什麼ExceptionInInitializerError在這裏?

ExceptionInInitializerErrors

它說:任何 例外,在靜態塊拋出包裝到 的ExceptionInInitializerError,然後將該的ExceptionInInitializerError被拋出。 但我的問題是:爲什麼

java.lang.ArrayIndexOutOfBoundsException

其扔在這裏**

class AX { 
    static int[] x = new int[0]; 
    static { 
     x[0] = 10; 
    } 

    public static void main(String[] args){ 
     AX ax = new AX(); 
    } 
} 

回答

3

這與容量0創建一個數組:

static int[] x = new int[0]; 

此分配值的x第一個元素:

static { 
    x[0] = 10; 
} 

Unfor如前所述,x的容量爲0,根本不能有任何元素。這就是爲什麼你得到ExceptionInInitializerError

如果你把堆棧跟蹤仔細一看, 它揭示更多的光線,因爲應該有這樣一行:

Caused by: java.lang.ArrayIndexOutOfBoundsException: 0 

這一數字0是數組索引超出範圍: 如果數組不能包含任何元素,則索引0超出範圍。

1

ArrayIndexOutOfBoundsException原因ExceptionInInitializerError異常。您實際得到的是:

java.lang.ExceptionInInitializerError

產生的原因:java.lang.ArrayIndexOutOfBoundsException:0

ExceptionInInitializerError文檔:

從版本1.4開始,此例外已被改裝爲c通知異常鏈接機制。可以在構建時提供並通過getException()方法訪問的「保存的可拋出對象」現在稱爲原因,並且可以通過Throwable.getCause()方法以及上述「傳統方法」訪問。 「

爲了證明報價:

class X { 
    static int[] x = new int[0]; 
    static { 
     x[0] = 10; 
    } 
} 

public class Test { 
    public static void main(String[] args) { 
     // try catch an error for demoing purposes 
     try { 
      X ax = new X(); 
     } catch (Error e) { 
      System.out.println(e.getClass()); 
      System.out.println(e.getCause()); 
     } 
    } 
} 

輸出:

類java.lang.ExceptionInInitializerError

的java.lang。ArrayIndexOutOfBoundsException異常:0

相關問題