这是来自 OCJP 示例。我写了下面的代码
public class Test {
static int x[];
static {
x[0] = 1;
}
public static void main(String... args) {
}
}
输出: java.lang.ExceptionInInitializerError
引起:java.lang.NullPointerException at x[0] = 1;
为什么抛出 NullPointerException
而不是 ArrayIndexOutOfBoundException
。
最佳答案
Why it is throwing NullPointerException and not ArrayIndexOutOfBoundException.
因为你没有初始化数组。
初始化数组
static int x[] = new int[10];
NullPointerException 的原因:
Thrown when an application attempts to use null in a case where an object is required. These include:
- 调用空对象的实例方法。
- 访问或修改空对象的字段。
- 将 null 的长度当作一个数组。
- 像访问数组一样访问或修改 null 的槽。
- 将 null 当作 Throwable 值来抛出。
你击中了更大胆的点,因为数组是 null
。
关于java.lang.ExceptionInInitializerError 由 : java. lang.NullPointerException 引起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20466906/