简体   繁体   English

Java中的ExceptionInInitializerError

[英]ExceptionInInitializerError in java

I was doing some tests from this page: http://scjptest.com/mock-test.xhtml?execution=e7s1 and there was a question "What is the result when this program is executed?". 我在此页面上进行了一些测试: http : //scjptest.com/mock-test.xhtml?execution=e7s1,并且出现了一个问题“执行该程序会产生什么结果?”。 Here is code: 这是代码:

public class SuperHotel {
    static int x[];

    static {
        x[0] = 1;
    }

    public static void main(String args[]) {        
    }   
}

Answer is "ExceptionInInitializerError is thrown". 答案是“抛出了ExceptionInInitializerError”。 Can somebody say me when "ExceptionInInitializerError" may happend and why it happend in this code? 有人可以说“ ExceptionInInitializerError”何时发生以及为什么在此代码中发生?

An ExceptionInInitializerError is thrown to indicate that an exception occurred during evaluation of a static initializer or the initializer for a static variable. 抛出ExceptionInInitializerError表示在评估静态初始化程序或静态变量的初始化程序期间发生了异常。

In your code, you have not initialized the array x[] , and you are using x[0]=1 in a static block, hence the exception occurred. 在您的代码中,您尚未初始化数组x[] ,并且在静态块中使用x[0]=1 ,因此发生了异常。

Signals that an unexpected exception has occurred in a static initializer. 表示在静态初始化程序中发生了意外的异常。 An ExceptionInInitializerError is thrown to indicate that an exception occurred during evaluation of a static initializer or the initializer for a static variable. 抛出ExceptionInInitializerError表示在评估静态初始化程序或静态变量的初始化程序期间发生了异常。

The error means that the class failed to initialize. 该错误表示该类无法初始化。

In this case, you have a NullPointerException in your static initializer block. 在这种情况下,您的静态初始化程序块中将具有NullPointerException。

x[0] = 1;  // NPE, because x is null

According to Javadoc ( https://docs.oracle.com/javase/7/docs/api/java/lang/ExceptionInInitializerError.html ) is thrown, when an Exception occurs in an static initializer Block. 根据Javadoc(当静态初始化程序块中发生异常)时,抛出( https://docs.oracle.com/javase/7/docs/api/java/lang/ExceptionInInitializerError.html )。

when you assing x[0] = 1 your x-Array is only a reference to an array. 当您设置x[0] = 1您的x-Array仅是对数组的引用。 It is not yet created and therefore a NullpointerExeption occurs in your static initializer Block, which leads to an ExceptionInInitializerError. 它尚未创建,因此在静态初始化程序块中会发生NullpointerExeption,这将导致ExceptionInInitializerError。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM