Javatpoint Logo
Javatpoint Logo

How To Resolve Java.lang.ExceptionInInitializerError in Java?

In Java, an exception can be defined as an unnecessary event which disturbs the normal flow of the program execution. The exceptions in Java are majorly categorized into two categories and they are checked and unchecked exceptions.

Error class in Java is the parent class of the ExceptionInInitializerError and it is considered as an unchecked exception. Whenever the Java Virtual Machine (JVM) tries to load a new class, all the static variables and static initializer block get evaluated by the JVM. The JVM automatically throws the ExceptionInInitializerError.

The ExceptionInInitializerError can also be indicated as a message that tells whenever an unexcepted exception takes place in the static block of the Java program or while value assignment for the static variables.

When ExceptionInInitializerError Occur?

In Java, the ExceptionInInitializerError can occur in two major cases or situations.

1. When Value is Being Assigned to a Static Variable

Let's understand in detail how ExceptionInInitializerError takes place while value is being assigned to a static variable with the help of a Java example program.

Filename: ExceptionInInitializerError1.java

Output:

How To Resolve Java.lang.ExceptionInInitializerError in Java

Explanation:

In the above-mentioned Java example program, a static variable is declared in the main method and the value of 1/0 is assigned to it. The value assigned will raise a divided by zero exception in the program. This will finally raise the ExceptionInInitializerError in the program.

2. When Null Value is Being Assigned Inside a Static Block

Filename: ExceptionInInitializerError2.java

Output:

How To Resolve Java.lang.ExceptionInInitializerError in Java

Explanation

In the above-mentioned Java example program, a static block has been created and declared. A string variable is declared and assigned with a null value inside the static block. In the later instructions the length of the null valued string is being printed. This will raise an NullPointerException as the value stored in the string variable is null and also the exception is taking place inside the static block, it will throw an ExceptionInInitializeError.

Ways to Resolve Java.lang.ExceptionInInitializerError in Java

In Java, the Java.lang.ExceptionInInitializerError can be ensuring that the static block in the program does not give chance for any runtime exceptions to be thrown.

Another way to resolve the Java.lang.ExceptionInInitializerError in Java would be by making sure that the static variable initialization of classes does not give chance for any runtime exceptions to be thrown.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA