java.lang.ExceptionInInitializerError Caused by: java.lang.NullPointerException

Viewed 100343

This is from OCJP example. I have written a following code

public class Test {

  static int x[];

  static {
     x[0] = 1;
  }

  public static void main(String... args) {
  }        
}       

Output: java.lang.ExceptionInInitializerError

Caused by: java.lang.NullPointerException at x[0] = 1;

Why it is throwing NullPointerException and not ArrayIndexOutOfBoundException.

8 Answers

ExceptionInInitializerError is an Unchecked Exception.

While executing, the static block, static variable initialization, if any exception comes then it is ExceptionInInitializerError.

example:

class Test{
static int x = 10/0;
}

output:

Runtime Exception: ExceptionInInitializerError caused by java.lang.ArithmeticExcpetion.

example:

 class Test{
           static{
                String s = null;
                System.out.println(s.length());
           }
    }

output:

Runtime Exception: ExceptionInInitializerError caused by java.lang.NullPointerException.
Related