Java.lang.ExceptionInInitializerError
In Java, we often need static members in the class to use them even before the instantiation of a class . But RuntimeException (unchecked exceptions) may be encountered while we initialize the static variables , possibly in a static initializer block. It is when, during the class loading , the JVM throws a java.lang.ExceptionInInitializerError .
Introduction to java.lang.ExceptionInInitializerError
java.lang.ExceptionInInitailizerError is an unchecked exception as it is a child class of Error . After a successful compilation, the Java Virtual Machine (JVM) performs dynamic loading, linking and initializing of classes and interfaces. The process is called class loading . The evaluation of all static initializer blocks and static variable assignments present in compiled code is part of this process. Hence JVM throws a java.lang.ExceptionInInitializerError, if, during the evaluation, an exception occurs. As a result, that particular class is also not loaded in the memory .
To take this further, when JVM fails to load a class, JVM throws another very common exception — NoClassDefFoundError . In that case, programmers should carefully inspect the logs before looking into the classpath, path and java.library.path because the reason might be a java.lang.ExceptionInInitializerError . The JVM also wraps an unchecked exception (within the instance of ExceptionInInitializerError that maintains a reference to it as the root cause) that occurred inside a static initializer block or static variable assignment.
Declaration
ExceptionInInitializerError is a part of java.lang package. If this error occurs then the class is not loaded in JVM memory because it is a child class of LinkageError .
It signals that an unexpected exception has occurred in a static initializer. java.lang.ExceptionInInitializerError is thrown to indicate that an exception occurred during the evaluation of a static initializer or the initializer for a static variable.
Constructors of java.lang.ExceptionInInitializerError
Constructor | Description |
---|---|
public ExceptionInInitializerError() | Constructs an ExceptionInInitializerError with null as its detail message string and with no saved throwable object. |
public ExceptionInInitializerError(String s) | Constructs an ExceptionInInitializerError with the specified detail message string. |
public ExceptionInInitializerError(Throwable thrown) | Constructs a new ExceptionInInitializerError class by saving a reference to the Throwable object thrown for later retrieval by the getException() method. |
Constructors in Detail
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 .
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 .
Parameters: thrown : The exception thrown
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.
Parameters: s : The detail message
Methods of java.lang.ExceptionInInitializerError
Method | Syntax | Description |
---|---|---|
getCause() | public Throwable getCause() | Returns the cause of this error (the exception that occurred during a static initialization that caused this error to be created). |
getException() | public Throwable getException() | Returns the exception that occurred during a static initialization that caused this error to be created. |
Methods in Detail
a. getCause() Method
It 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.
Return Value: The saved throwable object of this ExceptionInInitializerError, or null if this ExceptionInInitializerError has no saved throwable object.
b. getException() Method
It overrides the Throwable.getCause() method and returns the cause of this error (the exception that occurred during a static initialization that caused this error to be created).
Return Value: The cause of this error or null if the cause is nonexistent or unknown .
java.lang.ExceptionInInitializerError Examples
The following examples display the outputs received on running java FileName after compiling using javac FileName.java command.
1. Unchecked Exception during Static Variable Initialization
Output:
Explanation: The above example shows how an unchecked exception (dividing the number 10 by resulting in ArithmeticException ) during static variable assignment, results in java.lang.ExceptionInInitializerError error .
2. Unchecked Exception inside Static Initializer Block
a. Example Illustrating NullPointerException
Output:
Explanation: The example illustrates another unchecked exception that leads to java.lang.ExceptionInInitializerError. Here, we declare a static string variable s but do not initialize it. In the static block, we try to get the length of the uninitialized string variable, which results in NullPointerException , which is wrapped inside the instance of ExceptionInInitializerError and thrown by JVM.
b. Example Illustrating IndexOutOfBoundsException
Output:
Explanation: This example is similar to the previous one. But, here, we create a new empty ArrayList of strings and store its reference within a static variable. We create another static variable to hold the list's first item. We initialize the variable inside the static initializer block by fetching the first item from the list. But, since the list is empty, an IndexOutOfBoundsException is thrown by JVM in runtime wrapped inside the java.lang.ExceptionInInitializerError instance .
3. Checked Exception inside Static Initializer Block
Java doesn't allow throwing checked exceptions from a static block. However, one can handle those exceptions using a try-catch block and wrap them inside the ExceptionInInitializerError instance. It is a good practice as we follow the design principles of the Java language.
Output: i. If the ScalerTopics.txt is available
ii. If the ScalerTopics.txt is not available
Explanation: In this example, we declare a static FileInputStream variable instantiated inside the static initialization block. A file named "ScalerTopics.txt" may or may not exist. Hence, the constructor for FileInputStream possibly throws a checked exception — FileNotFoundException . But such checked exceptions are not allowed inside static blocks; therefore, one might get a compile-time error if the exception is unhandled. Hence, we handle it using try-catch and throw that exception, indirectly, wrapped inside an instance of java.lang.ExceptionInInitializerError. By this, we also conform ourselves to follow the design principles.
Causes of java.lang.ExceptionInInitializerError
The ExceptionInInitializerError indicates that an unexpected exception has occurred while:
- Evaluation of a static initializer block
- Initialization of a static variable
By default, the unexpected exception occurred is an unchecked exception . The unchecked exceptions are also called runtime exceptions in Java.
How to Resolve java.lang.ExceptionInInitializerError?
The resolution of java.lang.ExceptionInInitializer can be done by ensuring that:
- Static initializer of a class doesn't throw any unchecked exception ( runtime exception ).
- Initialization of a static variable in a class doesn't throw any unchecked exception (runtime exception).
For example, let's resolve an error thrown in the first example to see point 1 in action:
Output:
Explanation: The resolution is straightforward. In Example1, the java.lang.ExceptionInInitializerError is thrown because of an ArithmeticException caused due to division by zero . So, we change the divisor to some number other than zero during the initialization of variable s .
Let's explore another example for resolution of error thrown in example 2 to see point 2 in action:
Когда 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.
When Does Java Throw the ExceptionInInitializerError?
Repeatedly, code that works in dev breaks down in production. Java performance issues are difficult to track down or predict.
Simply put, Digma provides immediate code feedback. As an IDE plugin, it identifies issues with your code as it is currently running in test and prod.
The feedback is available from the minute you are writing it.
Imagine being alerted to any regression or code smell as you’re running and debugging locally. Also, identifying weak spots that need attending to, based on integration testing results.
Of course, Digma is free for developers.
An interesting read.
As always, the writeup is super practical and based on a simple application that can work with documents with a mix of encrypted and unencrypted fields.
We rely on other people’s code in our own work. Every day.
It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.
The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.
Lightrun is a new kind of debugger.
It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.
Learn more in this quick, 5-minute Lightrun tutorial:
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:
DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.
The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.
And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.
Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:
> CHECK OUT THE COURSE
1. Overview
In this quick tutorial, we’re going to see what causes Java to throw an instance of the ExceptionInInitializerError exception.
We’ll start with a little bit of theory. Then we’ll see a few examples of this exception in practice.
2. The ExceptionInInitializerError
The ExceptionInInitializerError indicates that an unexpected exception has occurred in a static initializer. Basically, when we see this exception, we should know that Java failed to evaluate a static initializer block or to instantiate a static variable.
In fact, every time any exception happens inside a static initializer, Java automatically wraps that exception inside an instance of the ExceptionInInitializerError class. This way, it also maintains a reference to the actual exception as the root cause.
Now that we know the rationale behind this exception, let’s see it in practice.
3. Static Initializer Block
To have a failed static block initializer, we’re going to divide an integer by zero intentionally:
Now if we trigger the class initialization with something like:
Then, we would see the following exception:
As mentioned earlier, Java throws the ExceptionInInitializerError exception while maintaining a reference to the root cause:
It’s also worth mentioning that the <clinit> method is a class initialization method in the JVM.
4. Static Variable Initialization
The same thing happens if Java fails to initialize a static variable:
Again, if we trigger the class initialization process:
Then the same exception occurs:
Similar to static initializer blocks, the root cause of the exception is also preserved:
5. Checked Exceptions
As part of the Java language specification (JLS-11.2.3), we can’t throw checked exceptions inside a static initializer block or static variable initializer. For instance, if we try to do so:
The compiler would fail with the following compilation error:
As a convention, we should wrap the possible checked exceptions inside an instance of ExceptionInInitializerError when our static initialization logic throws a checked exception:
As shown above, the getDeclaredConstructor() method throws a checked exception. Therefore, we caught the checked exception and wrapped it as the convention suggests.
Since we’re already returning an instance of ExceptionInInitializerError exception explicitly, Java won’t wrap this exception inside yet another ExceptionInInitializerError instance.
However, if we throw any other unchecked exception, Java will throw another ExceptionInInitializerError:
Here, we’re wrapping the checked exception inside an unchecked one. Because this unchecked exception is not an instance of ExceptionInInitializerError, Java will wrap it again, resulting in this unexpected stack trace:
As shown above, if we follow the convention, then the stack trace would be much cleaner than this.
5.1. OpenJDK
Recently, this convention is even used in the OpenJDK source code itself. For instance, here’s how the AtomicReference is using this approach:
6. Conclusion
In this tutorial, we saw what causes Java to throw an instance of the ExceptionInInitializerError exception.
As usual, all the examples are available over on GitHub.
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:
Когда Java выдает ошибку ExceptionInInitializerError?
В этом кратком руководстве мы увидим, что заставляет Java создавать экземпляр исключения ExceptionInInitializerError .
Начнем с небольшого количества теории. Затем мы увидим несколько примеров этого исключения на практике.
2. Ошибка ExceptionInInitializer
ExceptionInInitializerError указывает , что в статическом инициализаторе возникло непредвиденное исключение . По сути, когда мы видим это исключение, мы должны знать, что Java не удалось оценить блок статического инициализатора или создать экземпляр статической переменной.
Фактически каждый раз, когда внутри статического инициализатора возникает какое-либо исключение, Java автоматически заключает это исключение в экземпляр класса ExceptionInInitializerError . Таким образом, он также поддерживает ссылку на фактическое исключение как на основную причину.
Теперь, когда мы знаем причину этого исключения, давайте посмотрим на это на практике.
3. Статический блок инициализатора
Чтобы инициализатор статического блока вышел из строя, мы намеренно разделим целое число на ноль: