Class ExceptionInInitializerError
Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples. Other versions.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2022, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.
Exceptionininitializererror java что это
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 выбрасывает ошибку ExceptionInInitializerError?
В этом кратком руководстве мы увидим, что заставляет 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.
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.
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.
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:
- Make sure that initializing static variables in a program doesn’t throw any Runtime Exception.
- 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.
A technophile and a Big Data developer by passion. Loves developing advance C++ and Java applications in free time works as SME at Chegg where I help students with there doubts and assignments in the field of Computer Science.