java runtime_error ai_generated true

java.lang.ExceptionInInitializerError

ID: java/exception-in-initializer-error

Also available as: JSON · Markdown
85%Fix Rate
88%Confidence
80Evidence
2005-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
17 active

Root Cause

A static initializer block or static field initialization threw an unchecked exception. The class cannot be loaded, and subsequent attempts to use it throw NoClassDefFoundError.

generic

Workarounds

  1. 90% success Check the 'Caused by' chain to find the actual exception in the static initializer
    The ExceptionInInitializerError wraps the real exception. Look at the full stack trace:
    java.lang.ExceptionInInitializerError
      Caused by: java.lang.NullPointerException
        at com.example.Config.<clinit>(Config.java:15)
    # Fix the bug at line 15 of Config.java's static block

    Sources: https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/ExceptionInInitializerError.html

  2. 85% success Move error-prone initialization from static blocks to lazy initialization
    // Instead of:
    static final Connection conn = DriverManager.getConnection(url);
    // Use lazy init:
    private static Connection conn;
    public static synchronized Connection getConnection() {
        if (conn == null) conn = DriverManager.getConnection(url);
        return conn;
    }

Dead Ends

Common approaches that don't work:

  1. Catching ExceptionInInitializerError and retrying the class load 95% fail

    Once a class's static initialization fails, the JVM marks it as erroneous. All subsequent uses throw NoClassDefFoundError. The class cannot be re-initialized without restarting the JVM.

  2. Adding more memory thinking it's a resource issue 90% fail

    The error is caused by an exception in static code, not by resource limits. The root cause is a bug in the static initializer.

Error Chain

Leads to:
Frequently confused with: