Java lang exception initialize error

Когда Java выбрасывает ошибку ExceptionInInitializerError? Узнайте, что заставляет Java выдавать ExceptionInInitializerError, используя несколько практических примеров Автор: Ali Dehghani Дата записи 1. Обзор В этом кратком руководстве мы увидим, что заставляет Java выбрасывать экземпляр ExceptionInInitializerError исключение. Начнем с небольшой теории. Затем мы увидим несколько примеров этого исключения на практике. 2. Ошибка exceptioninitializererror ExceptionInInitializerError указывает, что […]

Содержание

  1. Когда Java выбрасывает ошибку ExceptionInInitializerError?
  2. 1. Обзор
  3. 2. Ошибка exceptioninitializererror
  4. 3. Блок Статического Инициализатора
  5. 4. Инициализация статической Переменной
  6. 5. Проверенные исключения
  7. 5.1. OpenJDK
  8. 6. Заключение
  9. How to Handle the Exception In Initializer Runtime Error in Java
  10. Introduction to Runtime Errors & Exceptions
  11. ExceptionInInitializerError Error: What, Why & How?
  12. How to handle the ExceptionInInitializerError Error
  13. java.lang.exceptionininitializererror – How to handle Exception Initializer Error
  14. How to deal with the ExceptionInInitializerError
  15. Final comments on the Error
  16. How to Fix Exception in thread «main» java.lang.ExceptionInInitializerError in Java Program? Example
  17. Cause of «Exception in thread «main» java.lang.ExceptionInInitializerError»
  18. Things to remember:
  19. Exception InInitializer Error Class
  20. Definition
  21. Remarks
  22. Constructors
  23. Fields
  24. Properties
  25. Methods
  26. Explicit Interface Implementations
  27. Extension Methods

Когда Java выбрасывает ошибку ExceptionInInitializerError?

Узнайте, что заставляет Java выдавать ExceptionInInitializerError, используя несколько практических примеров

Автор: Ali Dehghani
Дата записи

1. Обзор

В этом кратком руководстве мы увидим, что заставляет Java выбрасывать экземпляр ExceptionInInitializerError исключение.

Начнем с небольшой теории. Затем мы увидим несколько примеров этого исключения на практике.

2. Ошибка exceptioninitializererror

ExceptionInInitializerError указывает, что в статическом инициализаторе произошло непредвиденное исключение . В принципе, когда мы видим это исключение, мы должны знать, что Java не удалось вычислить статический блок инициализатора или создать экземпляр статической переменной.

Фактически, каждый раз, когда какое-либо исключение происходит внутри статического инициализатора, Java автоматически обертывает это исключение внутри экземпляра класса ExceptionInInitializerError . Таким образом, он также поддерживает ссылку на фактическое исключение в качестве основной причины.

Теперь, когда мы знаем причину этого исключения, давайте рассмотрим его на практике.

3. Блок Статического Инициализатора

Чтобы иметь неудачный инициализатор статического блока, мы намеренно разделим целое число на ноль:

Теперь, если мы инициализируем инициализацию класса с помощью чего-то вроде:

Тогда мы увидим следующее исключение:

Как упоминалось ранее, Java создает исключение ExceptionInInitializerError , сохраняя при этом ссылку на первопричину:

Также стоит упомянуть, что метод является методом инициализации класса в JVM.

4. Инициализация статической Переменной

То же самое происходит, если Java не инициализирует статическую переменную:

Опять же, если мы запустим процесс инициализации класса:

Затем происходит то же самое исключение:

Аналогично статическим блокам инициализатора, первопричина исключения также сохраняется:

5. Проверенные исключения

В рамках спецификации языка Java (JLS-11.2.3) мы не можем выбрасывать проверенные исключения внутри блока статического инициализатора или инициализатора статической переменной. Например, если мы попытаемся сделать это:

Компилятор потерпит неудачу со следующей ошибкой компиляции:

В качестве соглашения мы должны обернуть возможные проверенные исключения внутри экземпляра Исключение ininitializererror когда наша статическая логика инициализации выдает проверенное исключение:

Как показано выше, метод getDeclaredConstructor() вызывает проверенное исключение. Поэтому мы поймали проверенное исключение и завернули его, как предполагает конвенция.

Поскольку мы уже возвращаем экземпляр Исключение ininitializererror исключение явно, Java не будет заключать это исключение в еще одно Исключение ininitializererror пример.

Однако, если мы создадим любое другое непроверенное исключение, Java выдаст другое ExceptionInInitializerError :

Здесь мы заключаем проверенное исключение в непроверенное. Поскольку это непроверенное исключение не является экземпляром ExceptionInInitializerError, Java снова обернет его, что приведет к этой неожиданной трассировке стека:

Как показано выше, если мы будем следовать соглашению, то трассировка стека будет намного чище, чем это.

5.1. OpenJDK

В последнее время это соглашение даже используется в самом исходном коде OpenJDK. Например, вот как AtomicReference использует этот подход:

6. Заключение

В этом уроке мы увидели, что заставляет Java выбрасывать экземпляр ExceptionInInitializerError exception.

Как обычно, все примеры доступны на GitHub .

Источник

How to Handle the Exception In Initializer Runtime Error in Java

Table of Contents

Introduction to Runtime Errors & Exceptions

Unlike compile-time errors which are detected during compilation [1], runtime errors occur during program execution, i.e. runtime. Java’s runtime error hierarchy is somewhat complicated compared to other programming languages, but at the basic level there are two main categories: runtime errors and runtime exceptions, the latter of which being further divided into checked and unchecked exceptions (see Figure 1 below). Unchecked exceptions are also lumped into the somewhat confusingly named RuntimeException superclass, while all runtime errors are also considered to be unchecked. The term “unchecked” refers to errors and exceptions that Java doesn’t require to be caught or otherwise specified in the code [2]. Runtime Java errors and exceptions are otherwise jointly referred to as throwables, as per the name of the Throwable class—the parent class of all errors and exceptions in this language [3].

Figure 1. Java runtime errors & exceptions hierarchy [4]

ExceptionInInitializerError Error: What, Why & How?

After successfully compiling a program, the Java Virtual Machine (JVM) performs dynamic loading, linking, and initializing of classes and interfaces, broadly known as the class loading process [5]. This process includes the evaluation of all static initializer blocks and variable assignments present in the compiled code. If, during this evaluation, any unexpected exception occurs, the JVM throws an ExceptionInInitializerError runtime error, points to the specific exception that caused the error, and subsequently exits the program.

The ExceptionInInitializerError error occurs every time there is an unchecked (and uncaught) exception taking place inside a static initializer or a static variable assignment. The JVM wraps this exception inside an instance of the java.lang.ExceptionInInitializerError class (which itself is a subclass of the more generic java.lang.LinkageError class of errors [6]) and maintains a reference to it as the root cause.

How to handle the ExceptionInInitializerError Error

To avoid this error, simply ensure that:

  • static initializers of classes do not throw any unchecked exception, and that
  • static class variable initializations do not throw any unchecked exceptions.

Источник

java.lang.exceptionininitializererror – How to handle Exception Initializer Error

In this tutorial we will discuss about Java’s ExceptionInInitializerError and how to deal with it. The ExceptionInInitializerError is a sub-class of the LinkageError class and denotes that an unexpected exception has occurred in a static initializer or the initializer for a static variable. As of Java release 1.4, this error conforms to the general purpose exception-chaining mechanism.

The ExceptionInInitializerError is thrown when the JVM attempts to load a new class. During the class loading procedure, all static variables and static initializers are being evaluated. A static initializer is a block enclosed within curly braces without having any name and return type, except having the keyword static .

A sample example of a static initializer is shown below:

The static initializer is evaluated only once during the class loading procedure. Thus, a thrown exception in the evaluation of a static variable or initializer is wrapped into an ExceptionInInitializerError , in order for the JVM to indicate that the class could not be initialized and loaded.

A sample example that throws the aforementioned error is the following:

If we execute the above code snippet, we will receive the following error:

We can use the following methods, in order to retrieve more information about the underlying exception:

  • getException() : Returns the exception that occurred during a static initialization that caused this error to be created. However, after the exception has conformed to the general-purpose exception chaining, the preferred method to use is getCause .
  • getCause() :Returns the exception that caused this error to be thrown.

How to deal with the ExceptionInInitializerError

The ExceptionInInitializerError is used as a wrapper to indicate that an exception arises in the static initializer block or the evaluation of a static variable’s value. Thus, we have to ensure that the original exception is fixed, in order for the JVM to be able to load our class successfully.

It is very important to mention that you can throw unchecked / runtime exceptions from the block of a static initializer. However, you cannot allow a checked exception to propagate out of a static block, because is not possible to handle these exceptions in your source.

Источник

How to Fix Exception in thread «main» java.lang.ExceptionInInitializerError in Java Program? Example

JVM throws java.lang.ExceptionInInitializerError , when there is an Exception inside static initializer block. If you know about static variables in Java, then you may know that they are initialized at the time of class loading. If there is an Exception during that initialization of static variables, you will see ExceptionInInitializerError in Java. This could be any exception e.g. java.lang.ArrayIndexOutOfBound or java.lang.NullPointerException . Java developers are often confused with this error because they think that they have not defined any static initializer block, then how come they are getting ExceptionInInitializerError; well, by default Java combines all static variable initialization inside a static initializer block and initialize them in the order they are declared in the source file.

I suppose a variable ABC is declared at line 1, used at line 2 but initialized at line 3, then code at line 2 will throw java.lang.NullPointerException , which will be wrapped by JVM in ExceptionInInitializerError , and if that code happens to be executed by the main thread then you will see «Exception in thread «main» java.lang.ExceptionInInitializerError» in your console or log file.

In a large application with huge log files sometimes this error got unnoticed, and programmers get alerted by the dreaded java.lang.NoClassDefFoundError. Unfortunately, this error comes when the client class tries to use the class, which was not loaded because of ExceptionInInitializerError . Since class loading was failed earlier, JVM is now throwing NoClassDefFoundError .

Sometimes this misleads Java developers, and they start looking at classpath, path and java.library.path for missing class and confused them with hell not finding any anomalies. If you are investigating the cause of NoClassDefFoundError, it’s always a better idea to check your application log files for ExceptionInInitializerError before looking at CLASSPATH .

In this article, we will see an example code, which generates exceptions during static initialization and results in «Exception in thread «main» java.lang.ExceptionInInitializerError» . In the later part, we will see how to fix this error.

Cause of «Exception in thread «main» java.lang.ExceptionInInitializerError»

Now if you look at full stack trace carefully, you don’t need to do anything because JVM prints name of the class, which caused ExceptionInInitializerError . It’s also a subclass of LinkageError , which means if this error has occurred then your class will not be loaded into JVM memory. Now let’s take a look at our example program, which upon execution, throwing the following error :

By looking at this stack trace, we know that the actual error is java.lang.IndexOutOfBoundsException , which came at line 12 of StaticInitiazerDemo class. It came because of call to get() method of ArrayList with index 0 and come because the size of ArrayList was also zero (Index: 0, Size: 0 part of stack-trace). Now by following this information, you know that our List is empty when we try to get the first CreditCard from this list.

Here is a class hierarchy of all Error class in Java. You can see that ExceptionInInitializerError inherit from LinkageError. Its also worth knowing that like RuntimeException, Errors are also unchecked and compiler doesn’t check for mandatory error handling code.

Things to remember:

1) Remember «Exception in thread «main» java.lang.ExceptionInInitializerError» means Exception has occurred in the main thread, and it is java.lang.ExceptionInInitializerError , which is a subclass of LinkageError and comes when JVM tries to load a class and it failed because of any RuntimeException in static initializer block e.g. IndexOutOfBoundsException or NullPointerException.

2) Remember that JVM combines all static variable initialization into one static initializer block in the order they appear in the source file. So, don’t think that absence of an explicit static initializer block will not cause this error. In fact, you must ensure the correct order of static variables i.e. if one variable initialization uses another variable then make sure that is initialized first.

3) Down the line, java.lang.ExceptionInInitializerError can cause ClassNotFoundException or NoClassDefFoundError, if some other code tries to use the class, which caused ExceptionInInitializerError . Why? because loading of that class is failed and it’s not available inside JVM memory. So always check your log files for this before even if you are looking to solve any problem related to class not found.

4) Remember Static initializer block can throw RuntimeException but not checked Exception because later required mandatory catch block for handling.

Источник

Exception InInitializer Error Class

Definition

Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.

Signals that an unexpected exception has occurred in a static initializer.

Portions of this page are modifications based on work created andВ shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.

Constructors

Constructs an ExceptionInInitializerError with null as its detail message string and with no saved throwable object.

A constructor used when creating managed representations of JNI objects; called by the runtime.

Constructs an ExceptionInInitializerError with the specified detail message string.

Constructs a new ExceptionInInitializerError class by saving a reference to the Throwable object thrown for later retrieval by the #getException() method.

Fields

Properties

Returns the cause of this throwable or null if the cause is nonexistent or unknown.

(Inherited from Throwable) Class (Inherited from Throwable) Exception

Returns the exception that occurred during a static initialization that caused this error to be created.

The handle to the underlying Android instance.

(Inherited from Throwable) JniIdentityHashCode (Inherited from Throwable) JniPeerMembers LocalizedMessage

Creates a localized description of this throwable.

(Inherited from Throwable) Message

Returns the detail message string of this throwable.

(Inherited from Throwable) PeerReference (Inherited from Throwable) StackTrace (Inherited from Throwable) ThresholdClass

This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

Methods

Appends the specified exception to the exceptions that were suppressed in order to deliver this exception.

(Inherited from Throwable) Dispose() (Inherited from Throwable) Dispose(Boolean) (Inherited from Throwable) FillInStackTrace()

Fills in the execution stack trace.

(Inherited from Throwable) GetStackTrace()

Provides programmatic access to the stack trace information printed by #printStackTrace() .

(Inherited from Throwable) GetSuppressed()

Returns an array containing all of the exceptions that were suppressed, typically by the try -with-resources statement, in order to deliver this exception.

(Inherited from Throwable) InitCause(Throwable)

Initializes the cause of this throwable to the specified value.

(Inherited from Throwable) PrintStackTrace()

Prints this throwable and its backtrace to the standard error stream.

(Inherited from Throwable) PrintStackTrace(PrintStream)

Prints this throwable and its backtrace to the specified print stream.

(Inherited from Throwable) PrintStackTrace(PrintWriter)

Prints this throwable and its backtrace to the specified print writer.

(Inherited from Throwable) SetHandle(IntPtr, JniHandleOwnership)

Sets the Handle property.

(Inherited from Throwable) SetStackTrace(StackTraceElement[])

Sets the stack trace elements that will be returned by #getStackTrace() and printed by #printStackTrace() and related methods.

(Inherited from Throwable) ToString() (Inherited from Throwable) UnregisterFromRuntime() (Inherited from Throwable)

Explicit Interface Implementations

IJavaPeerable.Disposed() (Inherited from Throwable)
IJavaPeerable.DisposeUnlessReferenced() (Inherited from Throwable)
IJavaPeerable.Finalized() (Inherited from Throwable)
IJavaPeerable.JniManagedPeerState (Inherited from Throwable)
IJavaPeerable.SetJniIdentityHashCode(Int32) (Inherited from Throwable)
IJavaPeerable.SetJniManagedPeerState(JniManagedPeerStates) (Inherited from Throwable)
IJavaPeerable.SetPeerReference(JniObjectReference) (Inherited from Throwable)

Extension Methods

Performs an Android runtime-checked type conversion.

Источник

Introduction to Runtime Errors & Exceptions

Unlike compile-time errors which are detected during compilation [1], runtime errors occur during program execution, i.e. runtime. Java’s runtime error hierarchy is somewhat complicated compared to other programming languages, but at the basic level there are two main categories: runtime errors and runtime exceptions, the latter of which being further divided into checked and unchecked exceptions (see Figure 1 below). Unchecked exceptions are also lumped into the somewhat confusingly named RuntimeException superclass, while all runtime errors are also considered to be unchecked. The term “unchecked” refers to errors and exceptions that Java doesn’t require to be caught or otherwise specified in the code [2]. Runtime Java errors and exceptions are otherwise jointly referred to as throwables, as per the name of the Throwable class—the parent class of all errors and exceptions in this language [3].

Java runtime and exceptions hierarchy

Figure 1. Java runtime errors & exceptions hierarchy [4]

ExceptionInInitializerError Error: What, Why & How?

After successfully compiling a program, the Java Virtual Machine (JVM) performs dynamic loading, linking, and initializing of classes and interfaces, broadly known as the class loading process [5]. This process includes the evaluation of all static initializer blocks and variable assignments present in the compiled code. If, during this evaluation, any unexpected exception occurs, the JVM throws an ExceptionInInitializerError runtime error, points to the specific exception that caused the error, and subsequently exits the program.

The ExceptionInInitializerError error occurs every time there is an unchecked (and uncaught) exception taking place inside a static initializer or a static variable assignment. The JVM wraps this exception inside an instance of the java.lang.ExceptionInInitializerError class (which itself is a subclass of the more generic java.lang.LinkageError class of errors [6]) and maintains a reference to it as the root cause.

How to handle the ExceptionInInitializerError Error

To avoid this error, simply ensure that:

  • static initializers of classes do not throw any unchecked exception, and that
  • static class variable initializations do not throw any unchecked exceptions.

ExceptionInInitializerError Error Examples

Unchecked exception during static variable initialization

Figure 2(a) shows how an unchecked exception such as an instance of the java.lang.ArithmeticException triggers the ExceptionInInitializerError error. The error message denotes the division by zero arithmetic exception as the cause for the error and points to the specific class and line of code where it happened. Eradicating this arithmetic error, as shown in Figure 2(b), solves the issue.

(a)

package rollbar;

public class EIIE {
    private static int x = 20 / 0;

    public static void main(String... args) {
        System.out.println(x);
    }
}
Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.lang.ArithmeticException: / by zero
    at rollbar.EIIE.<clinit>(EIIE.java:4)

(b)

package rollbar;

public class EIIE {
    private static int x = 20 / 10;

    public static void main(String... args) {
        System.out.println(x);
    }
}
2
Figure 2: ExceptionInInitializerError error with static variable assignment (a) error and (b) resolution

Unchecked exception inside static initializer

Having an unchecked exception thrown inside a static initializer will inevitably trigger the ExceptionInInitializerError runtime error. Figure 3(a) shows how invoking the String::length method on a non-initialized String variable (whose value defaults to null) throws the NullPointerException, which in turn triggers the ExceptionInInitializerError error, because the exception occurred inside the static initializer of the class. To handle this type of scenario, one can implement a simple null guard (Figure 3(b)), or use a try-catch block to explicitly catch and handle the exception (Figure 3(c)). Note that these approaches assume that there is no logical error in the rest of the code, and that the desired functionality is correctly implemented.

(a)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package rollbar;

public class EIIE2 {
    private static String str;
    private static long len;

    static {
        len = str.length();
    }

    public static void main(String... args) {
        System.out.println("String: " + str);
        System.out.println("Length: " + len);
    }
}
Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.lang.NullPointerException: Cannot invoke "String.length()" because "rollbar.EIIE2.str" is null
    at rollbar.EIIE2.<clinit>(EIIE2.java:8)

(b)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package rollbar;

public class EIIE2 {
    private static String str;
    private static long len;

    static {
        len = str == null ? -1 : str.length();
    }

    public static void main(String... args) {
        System.out.println("String: " + str);
        System.out.println("Length: " + len);
    }
}
String: null
Length: -1

(c)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package rollbar;

public class EIIE2 {
    private static String str;
    private static long len;

    static {
        try {
            len = str.length();
        } catch (NullPointerException e) {
            len = -1;
        }
    }

    public static void main(String... args) {
        System.out.println("String: " + str);
        System.out.println("Length: " + len);
    }
}
String: null
Length: -1
Figure 3: ExceptionInInitializerError error inside static initializer (a) error and (b)(c) two possible resolutions

Checked exception inside static initializer?

Since it is impossible to throw checked exceptions from a static block (this is not allowed and will result in a compile-time error), it is good practice to wrap them inside an ExceptionInInitializerError instance manually, as shown in Figure 4. This is a clean way of handling checked exceptions in static initializers where their use is warranted, and it stays true to the design principles of the language. For completeness, if the checked exception in question doesn’t get thrown, the ExceptionInInitializerError isn’t thrown either and the code executes normally (Figure 4(b)).

(a)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package rollbar;

import java.lang.reflect.Field;

public class EIIE3 {
    private static Field fieldInfo;

    static {
        try {
            fieldInfo = EIIE3.class.getDeclaredField("x");
        } catch (NoSuchFieldException e) {
            throw new ExceptionInInitializerError(e);
        }
    }

    public static void main(String... args) {
        System.out.println(fieldInfo.getName());
        System.out.println(fieldInfo.getType());
    }
}
Exception in thread "main" java.lang.ExceptionInInitializerError
    at rollbar.EIIE3.<clinit>(EIIE3.java:12)
Caused by: java.lang.NoSuchFieldException: x
    at java.base/java.lang.Class.getDeclaredField(Class.java:2569)
    at rollbar.EIIE3.<clinit>(EIIE3.java:10)

(b)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package rollbar;

import java.lang.reflect.Field;

public class EIIE3 {
    private static Field fieldInfo;

    static {
        try {
            fieldInfo = EIIE3.class.getDeclaredField("x");
        } catch (NoSuchFieldException e) {
            throw new ExceptionInInitializerError(e);
        }
    }

    private static double x;

    public static void main(String... args) {
        System.out.println(fieldInfo.getName());
        System.out.println(fieldInfo.getType());
    }
}
x
double
Figure 4: ExceptionInInitializerError thrown manually inside a static initializer

Conclusion

Runtime errors occur during the execution of a program and as such are more difficult to prevent than compile-time errors. In Java, some of these errors are triggered during the class loading process, or in colloquial terms, when the program is starting up. This allows for a certain category of errors to be detected at a very early stage, despite the program having been successfully compiled. One such error is the ExceptionInInitializerError error which signals that an unexpected exception has occurred during the evaluation of a static initializer or the initialization of a static variable. This error serves as a runtime wrapper for the underlying exception and halts the JVM until the underlying exception is resolved.

Track, Analyze and Manage Errors With Rollbar

![Rollbar in action](https://rollbar.com/wp-content/uploads/2022/04/section-1-real-time-errors@2x-1-300×202.png)

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Java errors easier than ever. Sign Up Today!

References

[1] Rollbar, 2021. How to Fix «Illegal Start of Expression» in Java. Rollbar Editorial Team. [Online]. Available: https://rollbar.com/blog/how-to-fix-illegal-start-of-expression-in-java/. [Accessed Jan. 7, 2022]

[2] Oracle, 2021. Unchecked Exceptions — The Controversy (The Java™ Tutorials > Essential Java Classes > Exceptions). Oracle and/or its affiliates. [Online]. Available: https://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html. [Accessed Jan. 7, 2022]

[3] Oracle, 2021. Throwable (Java SE 17 & JDK 17). Oracle and/or its affiliates. [Online]. Available: https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Throwable.html. [Accessed Jan. 7, 2022]

[4] M. Sanger, 2018. Java Exception Hierarchy. Manish Sanger. [Online]. Available: https://www.manishsanger.com/java-exception-hierarchy/. [Accessed Jan. 7, 2022]

[5] Oracle, 2021. Chapter 5. Loading, Linking, and Initializing. Oracle Corporation and/or its affiliates. [Online]. Available: https://docs.oracle.com/javase/specs/jvms/se17/html/jvms-5.html. [Accessed Jan. 7, 2022]

[6] Oracle, 2021. LinkageError (Java SE 17 & JDK 17). Oracle and/or its affiliates. [Online]. Available: https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/LinkageError.html. [Accessed Jan. 7, 2022]

Improve Article

Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    An unexpected, 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.

    Java

    class GFG {

        static int x = 20 / 0;

        public static void main(String[] args)

        {

            System.out.println("The value of x is " + x);

        }

    }

    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.

    Java

    class GFG {

        static

        {

            String s = null;

            System.out.println(s.length());

        }

        public static void main(String[] args)

        {

            System.out.println("GeeksForGeeks Is Best");

        }

    }

    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.

    1. Brief Introduction to ExceptionInInitializerError in Java
    2. Handle the ExceptionInInitializerError in Java
    3. Conclusion

    ExceptionInInitializer Error in Java

    In this article, we will learn about the ExceptionInInitializerError in Java.

    Brief Introduction to ExceptionInInitializerError in Java

    ExceptionInInitializerError is an unchecked exception in Java, and it’s the child of the Error class. It falls in the category of Runtime Exceptions.

    In Java, whenever the JVM (Java Virtual Machine) fails to evaluate a static initializer block or instantiate or assign a value to a static variable, an exception ExceptionInInitializerError occurs. This indicates that something has gone wrong in the static initializer.

    Whenever this exception occurs inside the static initializer, Java maintains the reference to the actual exception as the root cause by wrapping the exception inside the object of the ExceptionInInitializerError class.

    Examples of ExceptionInInitializerError in Java

    Based on the above discussion, ExceptionInInitializerError occurs in major cases. Let’s see some examples to understand it better.

    Example 1: Scenario where we are assigning values to the static variable.

    public class Test {
    
        static int x = 100/0;
        public static void main(String []args)
        {
            System.out.println("Value of x is "+x);
        }
    
    }
    

    Output:

    Exception in thread "main" java.lang.ExceptionInInitializerError
    Caused by: java.lang.ArithmeticException: / by zero
        at Test.<clinit>(Test.java:4)
    

    In the above code, we assigned a 100/0 value to a static variable x, which gives an undefined arithmetic behavior, so an exception occurs while assigning values to the static variable, which finally gives us the ExceptionInInitializerError.

    We can also observe in the output that the actual exception ArithmeticException is wrapped inside an instance of the ExceptionInInitializerError class.

    Example 2: Scenario where inside the static blocks, null values are assigned.

    public class Test {
    
        static
        {
            String str = null;
            System.out.println(str.length());
        }
    
        public static void main(String []args)
        { }
    
    }
    

    Output:

    Exception in thread "main" java.lang.ExceptionInInitializerError
    Caused by: java.lang.NullPointerException: Cannot invoke "String.length()" because "str" is null
        at Test.<clinit>(Test.java:7)
    

    In the above code, we have created a static block inside which we have a string str with the null value. So, when we try to get its length using the length() method, we get NullPointerException as we print the length of a string with null as its value.

    But, as this exception occurs inside a static block, it will be wrapped inside the ExceptionInInitializerError class, and we get ExceptionInInitializerError in the output.

    Handle the ExceptionInInitializerError in Java

    ExceptionInInitializerError in Java can be avoided by ensuring the following points:

    1. Make sure that initializing static variables in a program doesn’t throw any Runtime Exception.
    2. Make sure that the static initializer blocks in a program don’t throw any Runtime Exception.

    Conclusion

    In this article, we learned about ExceptionInInitializerError in Java, indicating that some exceptions occurred while initializing a static variable or evaluating a static block. This error works as a runtime wrapper for the underlying exception and stops the JVM until the programmer resolves the underlying exception.

    I am using Netbeans. I did some things with bindings and now whenever I start my program, before it even initializes the form, it gives me an error

    The exception in thread main is occuring before the form is even an initialized object yet. The form is not even an object yet. Every line in my main() causes an exception. Random stuff. I don’t understand it at all.

    Here is the error.

        Exception in thread "main" java.lang.ExceptionInInitializerError
            at obd2ner.main(obd2ner.java:26)
    Caused by: java.lang.ClassCastException
            at java.lang.Class.cast(Class.java:2990)
            at org.jdesktop.beansbinding.Binding.convertForward(Binding.java:1312)
            at org.jdesktop.beansbinding.Binding.getSourceValueForTarget(Binding.java:844)
            at org.jdesktop.beansbinding.Binding.refreshUnmanaged(Binding.java:1222)
            at org.jdesktop.beansbinding.Binding.refresh(Binding.java:1207)
            at org.jdesktop.beansbinding.AutoBinding.tryRefreshThenSave(AutoBinding.java:162)
            at org.jdesktop.beansbinding.AutoBinding.bindImpl(AutoBinding.java:199)
            at org.jdesktop.beansbinding.Binding.bindUnmanaged(Binding.java:959)
            at org.jdesktop.beansbinding.Binding.bind(Binding.java:944)
            at org.jdesktop.beansbinding.BindingGroup.bind(BindingGroup.java:143)
            at OBD2nerForm.initComponents(OBD2nerForm.java:731)
            at OBD2nerForm.<init>(OBD2nerForm.java:75)
            at Status.<clinit>(Status.java:41)
            ... 1 more
    Java Result: 1
    

    OBD2nerForm line 731 is bindingGroup.bind();
    sometimes it errors out on pack();

    the exception in main() does not even seem relevant because it occurs as soon as the program is run and every time I comment out a line it jumps to the next

            public void actionPerformed(ActionEvent evt) {
                jFormattedTextField2ActionPerformed(evt);
            }
        });
    
        jLabel8.setText("Data In Que:");
    
        jLabel9.setFont(new Font("DejaVu Sans", 0, 14));
        jLabel9.setText("FFFFFFFFFFFFFFFFFFFF");
    
        GroupLayout jPanel5Layout = new GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(GroupLayout.LEADING)
            .add(jPanel5Layout.createSequentialGroup()
                .add(jPanel5Layout.createParallelGroup(GroupLayout.LEADING)
                    .add(jPanel5Layout.createSequentialGroup()
                        .add(19, 19, 19)
                        .add(jPanel5Layout.createParallelGroup(GroupLayout.TRAILING)
                            .add(jLabel7)
                            .add(jLabel5)
                            .add(jLabel6))
                        .add(18, 18, 18)
                        .add(jPanel5Layout.createParallelGroup(GroupLayout.LEADING)
                            .add(GroupLayout.TRAILING, jFormattedTextField1, GroupLayout.PREFERRED_SIZE, 22, GroupLayout.PREFERRED_SIZE)
                            .add(GroupLayout.TRAILING, jCheckBox1)
                            .add(GroupLayout.TRAILING, jCheckBox11))
                        .addPreferredGap(LayoutStyle.RELATED)
                        .add(jPanel5Layout.createParallelGroup(GroupLayout.TRAILING)
                            .add(jFormattedTextField2, GroupLayout.PREFERRED_SIZE, 22, GroupLayout.PREFERRED_SIZE)
                            .add(jCheckBox12)
                            .add(jCheckBox2))
                        .addPreferredGap(LayoutStyle.RELATED)
                        .add(jPanel5Layout.createParallelGroup(GroupLayout.TRAILING)
                            .add(jFormattedTextField3, GroupLayout.PREFERRED_SIZE, 22, GroupLayout.PREFERRED_SIZE)
                            .add(jCheckBox13)
                            .add(jCheckBox3))
                        .addPreferredGap(LayoutStyle.RELATED)
                        .add(jPanel5Layout.createParallelGroup(GroupLayout.TRAILING)
                            .add(jFormattedTextField4, GroupLayout.PREFERRED_SIZE, 22, GroupLayout.PREFERRED_SIZE)
                            .add(jCheckBox14)
                            .add(jCheckBox4))
                        .addPreferredGap(LayoutStyle.RELATED)
                        .add(jPanel5Layout.createParallelGroup(GroupLayout.TRAILING)
                            .add(jFormattedTextField5, GroupLayout.PREFERRED_SIZE, 22, GroupLayout.PREFERRED_SIZE)
                            .add(jCheckBox15)
                            .add(jCheckBox5))
                        .addPreferredGap(LayoutStyle.RELATED)
                        .add(jPanel5Layout.createParallelGroup(GroupLayout.TRAILING)
                            .add(jFormattedTextField6, GroupLayout.PREFERRED_SIZE, 22, GroupLayout.PREFERRED_SIZE)
                            .add(jCheckBox16)
                            .add(jCheckBox6))
                        .addPreferredGap(LayoutStyle.RELATED)
                        .add(jPanel5Layout.createParallelGroup(GroupLayout.TRAILING)
                            .add(jFormattedTextField7, GroupLayout.PREFERRED_SIZE, 22, GroupLayout.PREFERRED_SIZE)
                            .add(jCheckBox17)
                            .add(jCheckBox7))
                        .addPreferredGap(LayoutStyle.RELATED)
                        .add(jPanel5Layout.createParallelGroup(GroupLayout.TRAILING)
                            .add(jFormattedTextField8, GroupLayout.PREFERRED_SIZE, 22, GroupLayout.PREFERRED_SIZE)
                            .add(jCheckBox18)
                            .add(jCheckBox8))
                        .addPreferredGap(LayoutStyle.RELATED)
                        .add(jPanel5Layout.createParallelGroup(GroupLayout.LEADING)
                            .add(GroupLayout.TRAILING, jFormattedTextField9, GroupLayout.PREFERRED_SIZE, 22, GroupLayout.PREFERRED_SIZE)
                            .add(GroupLayout.TRAILING, jCheckBox19)
                            .add(GroupLayout.TRAILING, jCheckBox9))
                        .addPreferredGap(LayoutStyle.RELATED)
                        .add(jPanel5Layout.createParallelGroup(GroupLayout.LEADING)
                            .add(jCheckBox20)
                            .add(jCheckBox10)
                            .add(jFormattedTextField10, GroupLayout.PREFERRED_SIZE, 22, GroupLayout.PREFERRED_SIZE)))
                    .add(jPanel5Layout.createSequentialGroup()
                        .add(4, 4, 4)
                        .add(jPanel5Layout.createParallelGroup(GroupLayout.LEADING)
                            .add(jPanel5Layout.createSequentialGroup()
                                .add(jLabel8)
                                .addPreferredGap(LayoutStyle.RELATED)
                                .add(jLabel9, GroupLayout.PREFERRED_SIZE, 256, GroupLayout.PREFERRED_SIZE))
                            .add(jSeparator1, GroupLayout.PREFERRED_SIZE, 474, GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .add(GroupLayout.TRAILING, jPanel5Layout.createSequentialGroup()
                .addContainerGap(346, Short.MAX_VALUE)
                .add(jToggleButton3, GroupLayout.PREFERRED_SIZE, 132, GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(GroupLayout.LEADING)
            .add(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel5Layout.createParallelGroup(GroupLayout.BASELINE)
                    .add(jLabel5)
                    .add(jFormattedTextField1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .add(jFormattedTextField2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .add(jFormattedTextField3, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .add(jFormattedTextField4, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .add(jFormattedTextField5, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .add(jFormattedTextField6, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .add(jFormattedTextField7, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .add(jFormattedTextField8, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .add(jFormattedTextField9, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .add(jFormattedTextField10, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(LayoutStyle.RELATED)
                .add(jSeparator1, GroupLayout.PREFERRED_SIZE, 0, GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(LayoutStyle.RELATED)
                .add(jPanel5Layout.createParallelGroup(GroupLayout.LEADING)
                    .add(jCheckBox3)
                    .add(jCheckBox1)
                    .add(jCheckBox2)
                    .add(jCheckBox4)
                    .add(jCheckBox5)
                    .add(jCheckBox6)
                    .add(jCheckBox7)
                    .add(jCheckBox8)
                    .add(jCheckBox9)
                    .add(jLabel6)
                    .add(jCheckBox10))
                .addPreferredGap(LayoutStyle.RELATED)
                .add(jPanel5Layout.createParallelGroup(GroupLayout.TRAILING)
                    .add(jPanel5Layout.createParallelGroup(GroupLayout.LEADING)
                        .add(jLabel7)
                        .add(jPanel5Layout.createParallelGroup(GroupLayout.TRAILING)
                            .add(jCheckBox13)
                            .add(jCheckBox12)
                            .add(jCheckBox11)
                            .add(jCheckBox14)
                            .add(jCheckBox15)
                            .add(jCheckBox16)
                            .add(jCheckBox17)
                            .add(jCheckBox18)
                            .add(jCheckBox19)))
                    .add(jCheckBox20))
                .addPreferredGap(LayoutStyle.RELATED, 42, Short.MAX_VALUE)
                .add(jPanel5Layout.createParallelGroup(GroupLayout.BASELINE)
                    .add(jToggleButton3)
                    .add(jLabel8)
                    .add(jLabel9))
                .addContainerGap())
        );
    
        jTabbedPane1.addTab("tab6", jPanel5);
    
        add(jTabbedPane1, BorderLayout.CENTER);
    
        bindingGroup.bind();
    
        pack();
    }// </editor-fold>       
    

    Help, I do not understand. What information do you need from me?

    Edit: It seems to all be code which I cannot touch. I should probably add that this started with Netbeans adding about 200 invalid imports import jCheckbox1 which I deleted.

    Signals that an unexpected exception has occurred in a static initializer.
    An ExceptionInInitializerError is thrown to indicate that an
    exception occurred during evaluation of a static initializer or the
    initializer for a static variable.

    As of release 1.4, this exception has been retrofitted to conform to
    the general purpose exception-chaining mechanism. The «saved throwable
    object» that may be provided at construction time and accessed via
    the getException() method is now known as the cause,
    and may be accessed via the Throwable.getCause() method, as well
    as the aforementioned «legacy method.»

    Public Constructor Summary

    Public Method Summary

    Throwable

    getCause()

    Returns the cause of this error (the exception that occurred
    during a static initialization that caused this error to be created).

    Throwable

    getException()

    Returns the exception that occurred during a static initialization that
    caused this error to be created.

    Inherited Method Summary


    From class
    java.lang.Object

    Object

    clone()

    Creates and returns a copy of this Object.

    boolean

    equals(Object obj)

    Compares this instance with the specified object and indicates if they
    are equal.

    void

    finalize()

    Invoked when the garbage collector has detected that this instance is no longer reachable.

    final

    Class<?>

    getClass()

    Returns the unique instance of Class that represents this
    object’s class.

    int

    hashCode()

    Returns an integer hash code for this object.

    final

    void

    notify()

    Causes a thread which is waiting on this object’s monitor (by means of
    calling one of the wait() methods) to be woken up.

    final

    void

    notifyAll()

    Causes all threads which are waiting on this object’s monitor (by means
    of calling one of the wait() methods) to be woken up.

    String

    toString()

    Returns a string containing a concise, human-readable description of this
    object.

    final

    void

    wait(long timeout, int nanos)

    Causes the calling thread to wait until another thread calls the notify() or notifyAll() method of this object or until the
    specified timeout expires.

    final

    void

    wait(long timeout)

    Causes the calling thread to wait until another thread calls the notify() or notifyAll() method of this object or until the
    specified timeout expires.

    final

    void

    wait()

    Causes the calling thread to wait until another thread calls the notify() or notifyAll() method of this object.

    Public Constructors


    public


    ExceptionInInitializerError
    ()

    Constructs an ExceptionInInitializerError with
    null as its detail message string and with no saved
    throwable object.
    A detail message is a String that describes this particular exception.


    public


    ExceptionInInitializerError
    (Throwable thrown)

    Constructs a new ExceptionInInitializerError class by
    saving a reference to the Throwable object thrown for
    later retrieval by the getException() method. The detail
    message string is set to null.

    Parameters
    thrown The exception thrown


    public


    ExceptionInInitializerError
    (String s)

    Constructs an ExceptionInInitializerError with the specified detail
    message string. A detail message is a String that describes this
    particular exception. The detail message string is saved for later
    retrieval by the Throwable.getMessage() method. There is no
    saved throwable object.

    Parameters
    s the detail message

    Public Methods


    public

    Throwable

    getCause
    ()

    Returns the cause of this error (the exception that occurred
    during a static initialization that caused this error to be created).

    Returns
    • the cause of this error or null if the
      cause is nonexistent or unknown.


    public

    Throwable

    getException
    ()

    Returns the exception that occurred during a static initialization that
    caused this error to be created.

    This method predates the general-purpose exception chaining facility.
    The Throwable.getCause() method is now the preferred means of
    obtaining this information.

    Returns
    • the saved throwable object of this
      ExceptionInInitializerError, or null
      if this ExceptionInInitializerError has no saved
      throwable object.

    In this tutorial we will discuss about Java’s ExceptionInInitializerError and how to deal with it. The ExceptionInInitializerError is a sub-class of the LinkageError class and denotes that an unexpected exception has occurred in a static initializer or the initializer for a static variable. As of Java release 1.4, this error conforms to the general purpose exception-chaining mechanism.

    The ExceptionInInitializerError is thrown when the JVM attempts to load a new class. During the class loading procedure, all static variables and static initializers are being evaluated. A static initializer is a block enclosed within curly braces without having any name and return type, except having the keyword static.

    A sample example of a static initializer is shown below:

    import java.util.UUID;
    
    class Example {
    
         private static String ID = null;
    
         static {
              ID = UUID.randomUUID().toString();
         }
    }
    

    The static initializer is evaluated only once during the class loading procedure. Thus, a thrown exception in the evaluation of a static variable or initializer is wrapped into an ExceptionInInitializerError, in order for the JVM to indicate that the class could not be initialized and loaded.

    A sample example that throws the aforementioned error is the following:

    Example.java:

    public 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());
         }
    }
    

    If we execute the above code snippet, we will receive the following error:

    Exception in thread "main" java.lang.ExceptionInInitializerError
         Caused by: java.lang.NullPointerException
         at main.java.Example.<clinit>(Example.java:13)
    

    We can use the following methods, in order to retrieve more information about the underlying exception:

    • getException(): Returns the exception that occurred during a static initialization that caused this error to be created. However, after the exception has conformed to the general-purpose exception chaining, the preferred method to use is getCause.
    • getCause():Returns the exception that caused this error to be thrown.

    How to deal with the ExceptionInInitializerError

    The ExceptionInInitializerError is used as a wrapper to indicate that an exception arises in the static initializer block or the evaluation of a static variable’s value. Thus, we have to ensure that the original exception is fixed, in order for the JVM to be able to load our class successfully.

    Final comments on the Error

    It is very important to mention that you can throw unchecked/runtime exceptions from the block of a static initializer. However, you cannot allow a checked exception to propagate out of a static block, because is not possible to handle these exceptions in your source.

     
    This was a tutorial about Java’s ExceptionInInitializerError.

    Понравилась статья? Поделить с друзьями:
  • Java lang exception idtoken verification error
  • Java lang error что это
  • Java lang error что делать
  • Java lang error xiaomi
  • Java lang error watchdog