java.lang.ExceptionInInitializerError 由 : java. lang.NullPointerException 引起

标签 java exception nullpointerexception

这是来自 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/

相关文章:

java - 回到 Java(IntelliJ IDEA 或 Eclipse)

c++ - 构造函数抛出异常时子对象的销毁顺序

java - 二叉搜索树实例化

c# - ASP.Net MVC - "Cannot Create Instance of an Interface"

c# - 从纯 C 程序调用的 DLL 函数(在 C# .NET 中)导致错误

android - 带有 AppCompat BottomSheets 的 NullPointerException

java - 什么是NullPointerException,我该如何解决?

Java,查找数组中的最小数字

java - GUI 按钮放置

java - 快速写入持久队列