BackendBench
Coffee

Home โ€บ Java exceptions โ€บ ExceptionInInitializerError

Error ยท java.lang

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.NullPointerException

Extends 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

How to fix it

  1. Find the earliest log entry and read its Caused by chain; fix that exception.
  2. Avoid doing risky work in static initialisers; use lazy initialisation or dependency injection.
  3. Validate constants such as regular expressions with a unit test.
  4. Restart the application: a failed class cannot be re-initialised in the same JVM.

Broken and fixed

fails
private static final Pattern P = Pattern.compile("[a-z"); // invalid regex
works
private 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.

Related exceptions

More tools you might need