Exceptionininitializererror java что это

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.

Remarks

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 null as its detail message string and with no saved throwable object.

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

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)JniPeerMembersLocalizedMessage

Creates a localized description of this throwable.

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.

Initializes the cause of this throwable to the specified value.

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

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

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

Sets the Handle property.

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.

Источник

Встроенные исключения в Java с примерами

Встроенные исключения — это исключения, доступные в библиотеках Java. Эти исключения подходят для объяснения определенных ошибок. Ниже приведен список важных встроенных исключений в Java.
Примеры встроенных исключений:

// Java-программа для демонстрации
// ArithmeticException

public static void main(String args[])

int c = a / b; // нельзя делить на ноль

System.out.println( «Result = » + c);

catch (ArithmeticException e) <

System.out.println( «Can’t divide a number by 0» );

Выход:

// Java-программа для демонстрации
// ArrayIndexOutOfBoundException

public static void main(String args[])

a[ 6 ] = 9 ; // доступ к 7-му элементу в массиве

catch (ArrayIndexOutOfBoundsException e) <

System.out.println( «Array Index is Out Of Bounds» );

Выход:

// Java-программа для иллюстрации
// концепция ClassNotFoundException

public static void main(String[] args)

System.out.println( «Class created for» + o.getClass().getName());

Выход:

// Java-программа для демонстрации
// FileNotFoundException

public static void main(String args[])

// Следующий файл не существует

File file = new File( «E:// file.txt» );

FileReader fr = new FileReader(file);

catch (FileNotFoundException e) <

System.out.println( «File does not exist» );

Выход:

// Java-программа для иллюстрации IOException

public static void main(String args[])

FileInputStream f = null ;

f = new FileInputStream( «abc.txt» );

System.out.print(( char )i);

Выход:

// Java-программа для иллюстрации
// InterruptedException

public static void main(String args[])

Thread t = new Thread();

Выход:

// Java-программа для иллюстрации
// NoSuchMethodException

i = Class.forName( «java.lang.String» );

Class[] p = new Class[ 5 ];

catch (SecurityException e) <

catch (NoSuchMethodException e) <

catch (ClassNotFoundException e) <

public static void main(String[] args)

Выход:

// Java-программа для демонстрации NullPointerException

public static void main(String args[])

String a = null ; // нулевое значение

catch (NullPointerException e) <

Выход:

// Java-программа для демонстрации
// NumberFormatException

public static void main(String args[])

int num = Integer.parseInt( «akki» );

catch (NumberFormatException e) <

System.out.println( «Number format exception» );

Выход:

// Java-программа для демонстрации
// StringIndexOutOfBoundsException

public static void main(String args[])

String a = «This is like chipping » ; // длина 22

char c = a.charAt( 24 ); // доступ к 25-му элементу

catch (StringIndexOutOfBoundsException e) <

Выход:

Некоторые другие важные исключения

// Java-программа для иллюстрации
// ClassCastException

public static void main(String[] args)

String s = new String( «Geeks» );

Object o1 = new Object();

String s1 = (String)o1;

// Java-программа для иллюстрации
// StackOverflowError

public static void main(String[] args)

public static void m1()

public static void m2()

// Java-программа для иллюстрации
// NoClassDefFoundError

public static void main(String[] args)

System.out.println( «HELLO GEEKS» );

// Java-программа для иллюстрации
// ExceptionInInitializerError

static int x = 10 / 0 ;

public static void main(String[] args)

Код 2:

// Java-программа для иллюстрации
// ExceptionInInitializerError

public static void main(String[] args)

Объяснение: Вышеуказанное исключение возникает всякий раз, когда выполняется статическое присвоение переменной и статический блок, если возникает какое-либо исключение.

// Java-программа для иллюстрации
// IllegalArgumentException

public static void main(String[] args)

Thread t = new Thread();

Thread t1 = new Thread();

t.setPriority( 7 ); // Верный

t1.setPriority( 17 ); // Исключение

Объяснение: Исключение возникает явно либо программистом, либо разработчиком API, чтобы указать, что метод был вызван с недопустимым аргументом.

// Java-программа для иллюстрации
// IllegalStateException

public static void main(String[] args)

Thread t = new Thread();

Объяснение: Вышеуказанное исключение явно возникает либо программистом, либо разработчиком API, чтобы указать, что метод был вызван в неправильное время.

// Java-программа для иллюстрации
// AssertionError

public static void main(String[] args)

// Если х не больше или равно 10

// тогда мы получим исключение во время выполнения

Объяснение: Вышеуказанное исключение явно вызывается программистом или разработчиком API, чтобы указать, что утверждение assert не выполнено.

Пожалуйста, пишите комментарии, если вы обнаружите что-то неправильное, или вы хотите поделиться дополнительной информацией по обсуждаемой выше теме.

Источник

ExceptionInInitializerError при запуске JavaFX приложения из другого класса

При создании экземпляра класса App в main класса Main в коде ниже возникает следующая ошибка:

До этого читал аналогичный вопрос на иноязычном StackOverflow, но приведенные там методы решения не помогли.

Exceptionininitializererror java что это. Смотреть фото Exceptionininitializererror java что это. Смотреть картинку Exceptionininitializererror java что это. Картинка про Exceptionininitializererror java что это. Фото Exceptionininitializererror java что это

1 ответ 1

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

Например, если в классе есть такое поле:

Пути исправления.

Для исправления ошибки нужно найти оригинальное исключение. Возможные варианты:

Избавиться от статической инициализации. Если поля не используются в нескольких разных объектах, то их не нужно делать статическими. Попробуйте убрать static из объявления поля и использующих его методов и посмотрите что получится.

Ошибки, возникшие при инициализации полей класса уже не будут оборачиваться в Error и Вы сможете увидеть оригинальное исключение.
В Вашем случае это, скорее всего, java.lang.IllegalStateException: Toolkit not initialized по причине того, что элементы создаются до инициализации платформы. Посмотрите аналогичный вопрос на английском: JavaFX issue with static keyword; with Minimal, Complete, and Verifiable example

Просмотреть до конца трассировку стека по ошибке. Метод getCause() возвращает оригинальное исключение и обычно это исключение включается в вывод по ошибке. Для примера выше выводится:

Обрабатывать ошибки при инициализации. Перенести инициализацию переменных в методы, либо блоки и обрабатывать ошибки самому.

После того как найдете оригинальное исключение его нужно будет как-то обрабатывать и/или устранять. Но это уже совсем другая история.

Источник

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

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

1. Обзор

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

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

2. Ошибка exceptioninitializererror

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

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

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

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

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

Также стоит упомянуть, что метод является методом инициализации класса в 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.

Источник

Java Exception Handling – ExceptionInInitializerError

Moving along through our in-depth Java Exception Handling series, today we’ll dive into the ExceptionInInitializerError, which is thrown when an error occurs within the static initializer of a class or object. Since an ExceptionInInitializerError isn’t ever the cause of a thrown error, catching such an exception provides an underlying causal exception that indicates what the actual source of the issue was.

Throughout this article we’ll examine the ExceptionInInitializerError by looking at where it resides in the overall Java Exception Hierarchy. We’ll then explore a simple and fully-functional code sample that illustrates how a static initializer works, and what might lead to a thrown ExceptionInInitializerError in such an initializer, so let’s get to it!

The Technical Rundown

All Java errors implement the java.lang.Throwable interface, or are extended from another inherited class therein. The full exception hierarchy of this error is:

Full Code Sample

Below is the full code sample we’ll be using in this article. It can be copied and pasted if you’d like to play with the code yourself and see how everything works.

When Should You Use It?

A static initializer is created by enclosing code anywhere inside a class definition surrounded by braces ( < & >) and also preceded by the static keyword. For example:

As you can see in the code above, there can be as many static initializer blocks as desired within a class definition. Each will be executed in a top-down manner when the class is first loaded.

Static initializers are not to be confused with instance initializers (or instance members ), which are executed when the class is instantiated (i.e. a new object of that class type is created). Instance initializers are also executed just before the constructor method.

An instance initializer is written inside a class definition using two braces ( < & >), but without a preceding static keyword:

Just as with static versions, multiple instance initializers can be defined and will be executed from top to bottom.

The purpose of a static initializer is typically to execute any initialization code that must occur before a class can be used. Critically, static initializers are only executed once ever, the first time that class is loaded. Thus, they are great for classes that are frequently used throughout the application, but only need some basic configuration code to be executed once before multiple instances are used elsewhere, such as a database connection class.

To test a static initializer in “real” code we’ve added a simple snippet and field to our trusty Book class:

A static initializer block has been added near to the top of the class definition, and merely attempts to ensure the publicationType static field is an upper case value:

With this static initializer in place let’s try creating a new Book instance:

Executing this main(String[] args) method produces the following output:

Now, rerunning the same main(String[] args) method instantiates our Book just fine and outputs the results:

This code produces the following output:

Check out all the amazing features Airbrake-Java has to offer and see for yourself why so many of the world’s best engineering teams are using Airbrake to revolutionize their exception handling practices! Try Airbrake free for 30 days!

Monitor Your App Free for 30 Days

Exceptionininitializererror java что это. Смотреть фото Exceptionininitializererror java что это. Смотреть картинку Exceptionininitializererror java что это. Картинка про Exceptionininitializererror java что это. Фото Exceptionininitializererror java что это

Discover the power of Airbrake by starting a free 30-day trial of Airbrake. Quick sign-up, no credit card required. Get started.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *