Friday, January 11, 2013

Exception in thread "main" java.lang.ExceptionInInitializerError


The API says:
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.

Lets take an example and see what is it exactly:
package exceptions;
/**
 * This class demonstrates java.lang.ExceptionInInitializerError
 * by taking in sample cases as follows.
 * @author xploreraj
 *
 */
public class ExceptionInInitDemo {
 //trying to divide by 0 coming from m1 (hard-coded)
 static{
  int a = 10/m1();
 }
 // m1() always returns 0
 private static int m1(){
  return 0;
 }
 public static void main(String[] args) {

 }
}

Output:
Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.lang.ArithmeticException: / by zero
at exceptions.ExceptionInInitDemo.<clinit>(ExceptionInInitDemo.java:11)
Amateur Analysis:

The cause is very clear. We have tried to do something, that would have generated java.lang.ArithmeticException in other cases, and we could have handled it, by using either try-catch or throwing it to another level.
But, in this case, the static part of the code is executed while loading the class itself, so the Java interpreter goes mad about this exception, and is unable to load the class, resulting in a java.lang.Error type (by this I mean one of the classes derived from Error) that can not be recovered, as it would have already killed the JVM instance. The Exception that causes the Error is always specified, as in this case java.lang.ArithmeticException since we tried to divide by zero. Similarly, the cause behind the Error can vary, say for example,
java.lang.NullPointerException
java.lang.ArrayIndexOutOfBoundsException
It all depends upon how we code our program. But then we have to make sure that such abnormalities which are in control are avoided, by including proper checks in all suspected parts of our code.

No comments:

Post a Comment

Liked or hated the post? Leave your words of wisdom! Thank you :)