Home โบ Java exceptions โบ ExceptionInInitializerError
ExceptionInInitializerError: causes and fixes
A static initialiser or static field initialiser threw an exception while the class was loading.
What it looks like
java.lang.ExceptionInInitializerError
Caused by: java.lang.NullPointerExceptionExtends LinkageError in java.lang.
What it means
When the JVM first uses a class it runs its static initialisers. If one throws an unchecked exception, the JVM wraps it in ExceptionInInitializerError and marks the class as unusable. Every later attempt to use that class fails with NoClassDefFoundError: Could not initialize class X, which hides the real cause. Always look at the first occurrence in the log and read its Caused by line.
Common causes
- A static field initialised from configuration, a file or the environment that is missing.
- A static block that opens a connection or reads a resource and fails.
- A singleton or utility class that builds its state in a static initialiser using something not yet ready.
- A static initialiser calling a method that throws, such as
Pattern.compilewith a bad regex.
How to fix it
- Find the earliest log entry and read its Caused by chain; fix that exception.
- Avoid doing risky work in static initialisers; use lazy initialisation or dependency injection.
- Validate constants such as regular expressions with a unit test.
- Restart the application: a failed class cannot be re-initialised in the same JVM.
Broken and fixed
private static final Pattern P = Pattern.compile("[a-z"); // invalid regexprivate static final Pattern P = Pattern.compile("[a-z]+");๐ Unravel the failing code ๐ Unravel the fix
Debug it faster
Paste the whole stack trace into the stack trace beautifier to hide framework frames, jump to the root cause and find the first line of your own code. It runs in your browser, so the trace never leaves your machine.
Frequently asked questions
Is ExceptionInInitializerError a checked or unchecked exception?
ExceptionInInitializerError is an Error (it extends LinkageError). Errors signal serious problems in the JVM or environment; applications normally should not catch them, and ordinary catch (Exception e) blocks will not.
Which package is ExceptionInInitializerError in?
It lives in java.lang, so the import is import java.lang.ExceptionInInitializerError; (java.lang needs no import).
What is the first thing to check when I see ExceptionInInitializerError?
Read the message and the first stack trace line in your own code. The usual causes are: A static field initialised from configuration, a file or the environment that is missing; and A static block that opens a connection or reads a resource and fails.