Java lang exceptionininitializererror как исправить
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.
IntelliJ Error:java: java.lang.ExceptionInInitializerError
Every time I encounter this exception in IntelliJ, I fix it trivially and forget the fix easily.
- Add new TestClass .
- Right-click TestClass .
- Select «Run ‘TestClass'» to run test cases.
The «Messages Build» pane shows:
What can possibly go wrong?
What are the likely issues in this simple scenario?
IntelliJ: COMMUNITY 2017.1 (idea-IC-171.4424.56)
6 Answers 6
To fix the issue, I do:
- File -> Project Structure. -> Project Settings / Project -> Project SDK.
- Change from «9-ea» to «1.8».
DETAILS
Apparently, the issue is discrepancies in selected JDK-s to build (java 9) and run (java 8).
I’m not sure how «9-ea» gets re-selected there for the same project — neither IntelliJ itself runs in «9-ea» JRE (according to Help -> About) nor JAVA_HOME env var is set to it nor other possible settings (like Maven -> Runner) suggest any «9-ea».
I also didn’t manage to run the test under the same JDK (java 9) which it gets compiled under. However, it’s unclear what JDK tests are run under because IntelliJ reports only about JDK for compilation.
If you use Lombok: For me it was a solution to set the newest version for my maven lombok dependency in the pom.xml.
I was facing same error when i tried to run my application in IntelliJ-2019.2 version. Below are the steps i followed to resolve this issue.
- Go to below path in IntelliJ
File -> Project Structure -> Project -> Project SDK -> (select java version which you want to use )
(In my case under ‘project SDK’ java-11 was selected, I changed it to ‘java8’)
- Click on ‘Apply’ and then ‘OK’.
I feel I ran into this issue because IntelliJ was trying to compile my java classes using in-built java-11 whereas my java classes are built on java-8. So when i explicitly configured java-8 in IntelliJ, It worked!! Hope this helps.
I started seeing this exception once I installed Java 11 in my machine. JAVA_HOME was by default pointing to Java 11 and my project was still in Java 8. Changing JAVA_HOME to Java 8 jdk fixed the issue for me.
If you have multiple projects each running on a different JDK, use this command to temporarily change the Java version per command.
JAVA_HOME=/path/to/JVM/jdk/Home mvn clean install
If you have recently updated your IDE then you can try these steps.
- Delete .idea directory for the idea project/workspace
- Then go to File -> Invalidate Caches / Restart.
- Once Idea is restarted re-add/import your module(s)
I faced a similar issue with JARs and Jena (while run from IntelliJ it works).
I was using Apache Jena v4.0.0 in my project and have built a JAR (with a main class for the JAR to act as a console app).
The JAR builts successfully with IntelliJ but when run throws java.lang.ExceptionInInitializerError . Caused by: java.lang.NullPointerException . NPE suggests that something was not initialized properly.
The jar built with previous version Jena 3.17.0 works perfectly.
What I did to fix it
I’ve opened both the JARs, compared their META-INF folders and encountered the difference in
The new version (jena v4.0.0) contains only one line:
The old version (jena v3.17.0) contains two different lines:
I’ve added the old two lines to the file and repacked new JAR with it:
It resolved my issue.
Update: recent Jena v4.4.0 builts with the same "bug".
I’m not an expert and there is probably a better way than patching a JAR by hand.
But I still hope that this solution will help someone like me.
How to Handle the Exception In Initializer Runtime Error in Java
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.
Когда 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.