I have the error while executing the java program in Intellij IDE. Any thoughts what might be the issue.
Error:Internal error: (java.lang.IllegalArgumentException) No enum constant org.jetbrains.jps.model.java.LanguageLevel.JDK_1_9
java.lang.IllegalArgumentException: No enum constant org.jetbrains.jps.model.java.LanguageLevel.JDK_1_9
at java.lang.Enum.valueOf(Enum.java:238)
at org.jetbrains.jps.model.java.LanguageLevel.valueOf(LanguageLevel.java:21)
at org.jetbrains.jps.model.serialization.java.JpsJavaModelSerializerExtension$JavaProjectExtensionSerializer.loadExtension(JpsJavaModelSerializerExtension.java:285)
at org.jetbrains.jps.model.serialization.java.JpsJavaModelSerializerExtension$JavaProjectExtensionSerializer.loadExtension(JpsJavaModelSerializerExtension.java:268)
at org.jetbrains.jps.model.serialization.JpsLoaderBase.loadComponents(JpsLoaderBase.java:59)
at org.jetbrains.jps.model.serialization.JpsProjectLoader.a(JpsProjectLoader.java:119)
at org.jetbrains.jps.model.serialization.JpsProjectLoader.loadProject(JpsProjectLoader.java:98)
at org.jetbrains.jps.model.serialization.impl.JpsSerializationManagerImpl.loadModel(JpsSerializationManagerImpl.java:41)
at org.jetbrains.jps.cmdline.JpsModelLoaderImpl.loadModel(JpsModelLoaderImpl.java:45)
at org.jetbrains.jps.cmdline.BuildRunner.load(BuildRunner.java:71)
at org.jetbrains.jps.cmdline.BuildSession.runBuild(BuildSession.java:198)
at org.jetbrains.jps.cmdline.BuildSession.run(BuildSession.java:113)
at org.jetbrains.jps.cmdline.BuildMain$MyMessageHandler$1.run(BuildMain.java:133)
at org.jetbrains.jps.service.impl.SharedThreadPoolImpl$1.run(SharedThreadPoolImpl.java:41)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
I have configured JDK1_8
. But still it is showing as 1_9
.
asked Oct 30, 2014 at 4:50
6
Right-click on the root of your project explorer and choose Open Module Settings
(it’s near the bottom of the menu on my machine). Choose Project
on the resulting window and look at your sdk and language level. Choose 1.8 for the project sdk, and 8.0 for the language level.
answered Oct 30, 2014 at 20:47
Software EngineerSoftware Engineer
15.4k7 gold badges70 silver badges100 bronze badges
2
I had the same issue.
Did what others here recommended to do.
What finally resolved it was removing the following plugin entry from my pom.xml:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<!-- or whatever version you use -->
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugins>
</build>
So I suggest you check all your pom.xml files
answered Feb 23, 2017 at 15:01
[2019] ->
Check your run configurations:
- Hit CRTL+SHIFT+A
- Write «Edit configurations» And choose the option «Edit Configurations…»
- Select your Application node and select the «Configuration» tab.
- Check the JRE dropdown. See if that option is still 1.9 or so. Or change it there for a more suitable version.
This worked for me.
answered Jul 31, 2019 at 21:12
chntgomezchntgomez
2,0283 gold badges19 silver badges30 bronze badges
Upgrading IntelliJ fixed this issue for me. Apparently the JDK version I used (15) was not support in my older IntelliJ install
answered Sep 25, 2020 at 10:36
Roy WasseRoy Wasse
3901 silver badge10 bronze badges
I had the same problem that was fixed by switching to the latest version of Java
In this Case you Should Change To JDK 9 or another latest Version.
answered Jun 8, 2021 at 3:10
Android Studio does not have official support for JDK_1.8 yet. There are some libraries around to use lambdas.
answered Oct 30, 2014 at 7:52
JuampaJuampa
2,0352 gold badges25 silver badges35 bronze badges
1
Improve Article
Save Article
Like Article
Improve Article
Save Article
Like 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.
Last Updated :
03 Mar, 2022
Like Article
Save Article
Автор оригинала: Ali Dehghani.
1. Обзор
В этом кратком руководстве мы увидим, что заставляет Java выбрасывать экземпляр ExceptionInInitializerError исключение.
Начнем с небольшой теории. Затем мы увидим несколько примеров этого исключения на практике.
2. Ошибка exceptioninitializererror
ExceptionInInitializerError указывает, что в статическом инициализаторе произошло непредвиденное исключение . В принципе, когда мы видим это исключение, мы должны знать, что Java не удалось вычислить статический блок инициализатора или создать экземпляр статической переменной.
Фактически, каждый раз, когда какое-либо исключение происходит внутри статического инициализатора, Java автоматически обертывает это исключение внутри экземпляра класса ExceptionInInitializerError . Таким образом, он также поддерживает ссылку на фактическое исключение в качестве основной причины.
Теперь, когда мы знаем причину этого исключения, давайте рассмотрим его на практике.
3. Блок Статического Инициализатора
Чтобы иметь неудачный инициализатор статического блока, мы намеренно разделим целое число на ноль:
public class StaticBlock { private static int state; static { state = 42 / 0; } }
Теперь, если мы инициализируем инициализацию класса с помощью чего-то вроде:
Тогда мы увидим следующее исключение:
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 не инициализирует статическую переменную:
public class StaticVar { private static int state = initializeState(); private static int initializeState() { throw new RuntimeException(); } }
Опять же, если мы запустим процесс инициализации класса:
Затем происходит то же самое исключение:
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) мы не можем выбрасывать проверенные исключения внутри блока статического инициализатора или инициализатора статической переменной. Например, если мы попытаемся сделать это:
public class NoChecked { static { throw new Exception(); } }
Компилятор потерпит неудачу со следующей ошибкой компиляции:
java: initializer must be able to complete normally
В качестве соглашения мы должны обернуть возможные проверенные исключения внутри экземпляра Исключение ininitializererror когда наша статическая логика инициализации выдает проверенное исключение:
public class CheckedConvention { private static Constructor constructor; static { try { constructor = CheckedConvention.class.getDeclaredConstructor(); } catch (NoSuchMethodException e) { throw new ExceptionInInitializerError(e); } } }
Как показано выше, метод getDeclaredConstructor() вызывает проверенное исключение. Поэтому мы поймали проверенное исключение и завернули его, как предполагает конвенция.
Поскольку мы уже возвращаем экземпляр Исключение 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 .
Thrown to indicate some unexpected internal error has occurred in
the Java Virtual Machine.
Public Constructor Summary
InternalError() Constructs an |
|
InternalError(Throwable cause) Constructs an |
Inherited Method Summary
From class
java.lang.Object
Object |
clone() Creates and returns a copy of this |
boolean |
equals(Object obj) Compares this instance with the specified object and indicates if they |
void |
finalize() Invoked when the garbage collector has detected that this instance is no longer reachable. |
final Class<?> |
getClass() Returns the unique instance of |
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 |
final void |
notifyAll() Causes all threads which are waiting on this object’s monitor (by means |
String |
toString() Returns a string containing a concise, human-readable description of this |
final void |
wait(long timeout, int nanos) Causes the calling thread to wait until another thread calls the |
final void |
wait(long timeout) Causes the calling thread to wait until another thread calls the |
final void |
wait() Causes the calling thread to wait until another thread calls the |
Public Constructors
public
InternalError
()
Constructs an InternalError
with no detail message.
public
InternalError
(String message)
Constructs an InternalError
with the specified
detail message.
Parameters
message | the detail message. |
---|
public
InternalError
(String message, Throwable cause)
Constructs an InternalError
with the specified detail
message and cause.
Note that the detail message associated
with cause
is not automatically incorporated in
this error’s detail message.
Parameters
message | the detail message (which is saved for later retrieval by the Throwable.getMessage() method). |
---|---|
cause | the cause (which is saved for later retrieval by theThrowable.getCause() method). (A null value ispermitted, and indicates that the cause is nonexistent or unknown.) |
public
InternalError
(Throwable cause)
Constructs an InternalError
with the specified cause
and a detail message of (cause==null ? null :
(which typically contains the class and
cause.toString())
detail message of cause
).
Parameters
cause | the cause (which is saved for later retrieval by theThrowable.getCause() method). (A null value ispermitted, and indicates that the cause is nonexistent or unknown.) |
---|
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].
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
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
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
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]