Wednesday 16 March 2016

ExceptionInInitializerError in Java

java.lang.Object à  java.lang.Throwable à java.lang.Error à java.lang.LinkageError à java.lang.ExceptionInInitializerError

public class ExceptionInInitializerError extends LinkageError

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.

Scenarios of ExceptionInInitializerError

Due to Exception in Static Initializer
If we get any runtime exception while executing static initializer (static block or static variable declaration executes while load the class) and JVM class loader will not able to initialize the class and throws ExceptionInInitializerError.

class DivideClass {

     /**Here ArithmeticException will lead
      * to ExceptionInInitializerError
      */
     static {
           int undefined = 1 / 0;
     }

     public String method() {
           return "from divide class";
     }
}

public class TestException {
     public static void main(String[] args) {
           DivideClass d = new DivideClass();
     }
}

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...