Java lang exceptionininitializererror jar

Java lang exceptionininitializererror jar

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

Constructor Summary

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

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

Method Summary

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

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

Methods inherited from class java.lang.Throwable

Methods inherited from class java.lang.Object

Constructor Detail

ExceptionInInitializerError

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.

ExceptionInInitializerError

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 .

ExceptionInInitializerError

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.

Method Detail

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.

getCause

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

Читайте также:  Python под виндовс 7

Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 1993, 2023, Oracle and/or its affiliates. All rights reserved. Use is subject to license terms. Also see the documentation redistribution policy.

Источник

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

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

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

2. Ошибка exceptioninitializererror

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

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

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

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

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

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

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

java.lang.ExceptionInInitializerError at com.baeldung. (ExceptionInInitializerErrorUnitTest.java:18) Caused by: java.lang.ArithmeticException: / by zero at com.baeldung.StaticBlock.(ExceptionInInitializerErrorUnitTest.java:35) . 23 more

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

assertThatThrownBy(StaticBlock::new) .isInstanceOf(ExceptionInInitializerError.class) .hasCauseInstanceOf(ArithmeticException.class);

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

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

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

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

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

java.lang.ExceptionInInitializerError at com.baeldung. (ExceptionInInitializerErrorUnitTest.java:11) Caused by: java.lang.RuntimeException at com.baeldung.StaticVar.initializeState(ExceptionInInitializerErrorUnitTest.java:26) at com.baeldung.StaticVar.(ExceptionInInitializerErrorUnitTest.java:23) . 23 more

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

assertThatThrownBy(StaticVar::new) .isInstanceOf(ExceptionInInitializerError.class) .hasCauseInstanceOf(RuntimeException.class);

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

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

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

java: initializer must be able to complete normally

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

public class CheckedConvention < private static Constructorconstructor; static < try < constructor = CheckedConvention.class.getDeclaredConstructor(); >catch (NoSuchMethodException e) < throw new ExceptionInInitializerError(e); >> >

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

Читайте также:  Javascript начало загрузки страницы

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

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

static < try < constructor = CheckedConvention.class.getConstructor(); >catch (NoSuchMethodException e) < throw new RuntimeException(e); >>

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

java.lang.ExceptionInInitializerError at com.baeldung.exceptionininitializererror. Caused by: java.lang.RuntimeException: java.lang.NoSuchMethodException: . Caused by: java.lang.NoSuchMethodException: com.baeldung.CheckedConvention.() at java.base/java.lang.Class.getConstructor0(Class.java:3427) at java.base/java.lang.Class.getConstructor(Class.java:2165)

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

5.1. OpenJDK

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

public class AtomicReference implements java.io.Serializable < private static final VarHandle VALUE; static < try < MethodHandles.Lookup l = MethodHandles.lookup(); VALUE = l.findVarHandle(AtomicReference.class, "value", Object.class); >catch (ReflectiveOperationException e) < throw new ExceptionInInitializerError(e); >> private volatile V value; // omitted >

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

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

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

Источник

Class ExceptionInInitializerError

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.

Constructor Summary

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

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

Method Summary

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

Methods declared in class java.lang.Throwable

Methods declared in class java.lang.Object

Constructor Details

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.

ExceptionInInitializerError

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 .

ExceptionInInitializerError

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.

Читайте также:  Какая версия html лучше

Method Details

getException

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

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, 2023, 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.

Источник

Class ExceptionInInitializerError

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.

Constructor Summary

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

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

Method Summary

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

Methods declared in class java.lang.Throwable

Methods declared in class java.lang.Object

Constructor Details

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.

ExceptionInInitializerError

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 .

ExceptionInInitializerError

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.

Method Details

getException

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

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, 2023, 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.

Источник

Оцените статью