How to resolve the "java.lang.exceptionininitializererror" error

The ExceptionInInitializerError is a sub-class of the LinkageError class. The error denotes that an unexpected exception has occurred in a static initializer or the initializer for a static variable.

The following code gives an error on line 1313.

class Example {
private static String message = null;
private static String subMessage = null;
public Example(String message) {
Example.message = message;
}
static {
/* Store the first 10 characters of the input message. */
subMessage = message.substring(0, 10);
}
public String getSubMessage() {
return subMessage;
}
public static void main(String[] args) {
Example exampleClass = new Example("Test");
System.out.println(exampleClass.getSubMessage());
}
}

How to solve this exception

  • Ensure that the static initialization block of classes does not throw a RuntimeException.

  • Ensure that initializing static variables of classes does not throw any RuntimeException.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved