How to Resolve Java.lang.ExceptionInInitializerError In Java?
An unexcepted, unwanted event that disturbed the normal flow of a program is called an Exception.
There are mainly two types of exception in Java:
1. Checked Exception
2. Unchecked Exception
ExceptionInInitializerError is the child class of the Error class and hence it is an unchecked exception. This exception is rise automatically by JVM when JVM attempts to load a new class as, during class loading, all static variables and static initializer block are being evaluated. This exception also acts as a signal that tells us that an unexpected exception has occurred in a static initializer block or in the assignment of value to the static variable.
There are basically two cases when ExceptionInInitializerError can occur in a Java Program:
1. ExceptionInInitializerError While Assigning Value To The Static Variable
In the below example we assign a static variable to 20/0 where 20/0 gives an undefined arithmetic behavior and hence there occurs an exception in the static variable assignment and ultimately we will get ExceptionInInitializerError.
2. ExceptionInInitializerError While Assigning Null Value Inside A Static Block
In the below example we have declared a static block inside which we create a string s and assign a null value to it, and then we are printing the length of string, so we will get NullPointerException because we were trying to print the length of a string that has its value as null and as we see that this exception occurs inside the static block, so we will get ExceptionInInitializerError.
How to Resolve Java.lang.ExceptionInInitializerError ?
- We can resolve the java.lang.ExceptionInInitializerError by ensuring that static initializer block of classes does not throw any Runtime Exception.
- We can resolve also resolve this exception by ensuring that the initializing static variable of classes also doesn’t throw any Runtime Exception.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.