Java lang exceptionininitializererror null как исправить

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

Improve Article

Save Article

  • Read
  • Discuss
  • Improve Article

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

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

    Java runtime and exceptions hierarchy

    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.

    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
    Figure 2: ExceptionInInitializerError error with static variable assignment (a) error and (b) resolution

    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
    Figure 3: ExceptionInInitializerError error inside static initializer (a) error and (b)(c) two possible resolutions

    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
    Figure 4: ExceptionInInitializerError thrown manually inside a static initializer

    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]

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

    В Java есть в основном два типа исключений:

    1. Проверяемое исключение

    2. Непроверенное исключение

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

    В основном есть два случая, когда ExceptionInInitializerError может возникнуть в программе Java:

    1. ExceptionInInitializerError при присвоении значения статической переменной

    В приведенном ниже примере мы назначаем статической переменной 20/0, где 20/0 дает неопределенное арифметическое поведение, и, следовательно, возникает исключение в назначении статической переменной, и в конечном итоге мы получим ExceptionInInitializerError.

    Ява

    class GFG {

    static int x = 20 / 0 ;

    public static void main(String[] args)

    {

    System.out.println( "The value of x is " + x);

    }

    }

    2. ExceptionInInitializerError при присвоении нулевого значения внутри статического блока

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

    Ява

    class GFG {

    static

    {

    String s = null ;

    System.out.println(s.length());

    }

    public static void main(String[] args)

    {

    System.out.println( "GeeksForGeeks Is Best" );

    }

    }

    Как разрешить Java.lang.ExceptionInInitializerError?

    • Мы можем разрешить java.lang.ExceptionInInitializerError, убедившись, что статический блок инициализатора классов не генерирует никаких исключений времени выполнения.
    • Мы также можем разрешить это исключение, убедившись, что инициализирующая статическая переменная классов также не генерирует никаких исключений времени выполнения.

    Вниманию читателя! Не прекращайте учиться сейчас. Ознакомьтесь со всеми важными концепциями Java Foundation и коллекций с помощью курса «Основы Java и Java Collections» по доступной для студентов цене и будьте готовы к работе в отрасли. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .

    1. Brief Introduction to ExceptionInInitializerError in Java
    2. Handle the ExceptionInInitializerError in Java
    3. Conclusion

    ExceptionInInitializer Error in Java

    In this article, we will learn about the ExceptionInInitializerError in Java.

    Brief Introduction to ExceptionInInitializerError in Java

    ExceptionInInitializerError is an unchecked exception in Java, and it’s the child of the Error class. It falls in the category of Runtime Exceptions.

    In Java, whenever the JVM (Java Virtual Machine) fails to evaluate a static initializer block or instantiate or assign a value to a static variable, an exception ExceptionInInitializerError occurs. This indicates that something has gone wrong in the static initializer.

    Whenever this exception occurs inside the static initializer, Java maintains the reference to the actual exception as the root cause by wrapping the exception inside the object of the ExceptionInInitializerError class.

    Examples of ExceptionInInitializerError in Java

    Based on the above discussion, ExceptionInInitializerError occurs in major cases. Let’s see some examples to understand it better.

    Example 1: Scenario where we are assigning values to the static variable.

    public class Test {
    
        static int x = 100/0;
        public static void main(String []args)
        {
            System.out.println("Value of x is "+x);
        }
    
    }
    

    Output:

    Exception in thread "main" java.lang.ExceptionInInitializerError
    Caused by: java.lang.ArithmeticException: / by zero
        at Test.<clinit>(Test.java:4)
    

    In the above code, we assigned a 100/0 value to a static variable x, which gives an undefined arithmetic behavior, so an exception occurs while assigning values to the static variable, which finally gives us the ExceptionInInitializerError.

    We can also observe in the output that the actual exception ArithmeticException is wrapped inside an instance of the ExceptionInInitializerError class.

    Example 2: Scenario where inside the static blocks, null values are assigned.

    public class Test {
    
        static
        {
            String str = null;
            System.out.println(str.length());
        }
    
        public static void main(String []args)
        { }
    
    }
    

    Output:

    Exception in thread "main" java.lang.ExceptionInInitializerError
    Caused by: java.lang.NullPointerException: Cannot invoke "String.length()" because "str" is null
        at Test.<clinit>(Test.java:7)
    

    In the above code, we have created a static block inside which we have a string str with the null value. So, when we try to get its length using the length() method, we get NullPointerException as we print the length of a string with null as its value.

    But, as this exception occurs inside a static block, it will be wrapped inside the ExceptionInInitializerError class, and we get ExceptionInInitializerError in the output.

    Handle the ExceptionInInitializerError in Java

    ExceptionInInitializerError in Java can be avoided by ensuring the following points:

    1. Make sure that initializing static variables in a program doesn’t throw any Runtime Exception.
    2. Make sure that the static initializer blocks in a program don’t throw any Runtime Exception.

    Conclusion

    In this article, we learned about ExceptionInInitializerError in Java, indicating that some exceptions occurred while initializing a static variable or evaluating a static block. This error works as a runtime wrapper for the underlying exception and stops the JVM until the programmer resolves the underlying exception.

    In my Android app the WebView activity class has following line,

    webView.addJavascriptInterface(new JSInterface(this), "Android");   
    

    And in JSInterface class, I’m initializing Google «SpreadSheetService» like below,

    import com.google.gdata.client.spreadsheet.SpreadsheetService;
    
    --- some more imports ---
    
    
    public class JSInterface {
        Context mContext;
    
        public SpreadsheetService service;
    
        /** Instantiate the interface and set the context */
        JSInterface(Context c) {
            mContext = c;
            service = new SpreadsheetService("List Demo");
        }
    
        ------- some more code -----
    

    When I run the application I’m getting the following exception,

    01-19 21:38:00.652: E/AndroidRuntime(4085): java.lang.ExceptionInInitializerError
    

    which has the below trace

    01-19 21:38:00.652: E/AndroidRuntime(4085): FATAL EXCEPTION: main
    01-19 21:38:00.652: E/AndroidRuntime(4085): java.lang.ExceptionInInitializerError
    01-19 21:38:00.652: E/AndroidRuntime(4085):     at com.android.quotes.JSInterface.<init>(JSInterface.java:33)
    01-19 21:38:00.652: E/AndroidRuntime(4085):     at com.android.quotes.CHQuotesActivity.onCreate(CHQuotesActivity.java:19)
    01-19 21:38:00.652: E/AndroidRuntime(4085):     at android.app.Activity.performCreate(Activity.java:4465)
    01-19 21:38:00.652: E/AndroidRuntime(4085):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
    01-19 21:38:00.652: E/AndroidRuntime(4085):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1919)
    01-19 21:38:00.652: E/AndroidRuntime(4085):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980)
    01-19 21:38:00.652: E/AndroidRuntime(4085):     at android.app.ActivityThread.access$600(ActivityThread.java:122)
    01-19 21:38:00.652: E/AndroidRuntime(4085):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146)
    01-19 21:38:00.652: E/AndroidRuntime(4085):     at android.os.Handler.dispatchMessage(Handler.java:99)
    01-19 21:38:00.652: E/AndroidRuntime(4085):     at android.os.Looper.loop(Looper.java:137)
    01-19 21:38:00.652: E/AndroidRuntime(4085):     at android.app.ActivityThread.main(ActivityThread.java:4340)
    01-19 21:38:00.652: E/AndroidRuntime(4085):     at java.lang.reflect.Method.invokeNative(Native Method)
    01-19 21:38:00.652: E/AndroidRuntime(4085):     at java.lang.reflect.Method.invoke(Method.java:511)
    

    I searched Google, but didnt get any solution for this.. Any idea on why I’m getting this exception??

    Peter

    JVM throws java.lang.ExceptionInInitializerError, when there is an Exception inside static initializer block. If you know about static variables in Java, then you may know that they are initialized at the time of class loading. If there is an Exception during that initialization of static variables, you will see ExceptionInInitializerError in Java. This could be any exception e.g. java.lang.ArrayIndexOutOfBound or java.lang.NullPointerException. Java developers are often confused with this error because they think that they have not defined any static initializer block, then how come they are getting ExceptionInInitializerError; well, by default Java combines all static variable initialization inside a static initializer block and initialize them in the order they are declared in the source file.

    I suppose a variable ABC is declared at line 1, used at line 2 but initialized at line 3, then code at line 2 will throw java.lang.NullPointerException, which will be wrapped by JVM in ExceptionInInitializerError, and if that code happens to be executed by the main thread then you will see «Exception in thread «main» java.lang.ExceptionInInitializerError» in your console or log file.

    In a large application with huge log files sometimes this error got unnoticed, and programmers get alerted by the dreaded java.lang.NoClassDefFoundError. Unfortunately, this error comes when the client class tries to use the class, which was not loaded because of ExceptionInInitializerError . Since class loading was failed earlier, JVM is now throwing NoClassDefFoundError.

    Sometimes this misleads Java developers, and they start looking at classpath, path and java.library.path for missing class and confused them with hell not finding any anomalies.  If you are investigating the cause of NoClassDefFoundError, it’s always a better idea to check your application log files for ExceptionInInitializerError before looking at CLASSPATH.

    In this article, we will see an example code, which generates exceptions during static initialization and results in «Exception in thread «main» java.lang.ExceptionInInitializerError». In the later part, we will see how to fix this error.

    Cause of «Exception in thread «main» java.lang.ExceptionInInitializerError»

    As with any other error or exception, by first looking at this line, you know that exception is java.lang.ExceptionInInitializerError, which comes because of failure during class loading and static initialization.

     Since it has occurred inside the main thread, which is responsible for starting the application, it’s better to start your investigation from the Main class, the class which you provided to java command at the command line or the same class where you have written your public static void main(String args[]) method. 

    Now if you look at full stack trace carefully, you don’t need to do anything because JVM prints name of the class, which caused ExceptionInInitializerError. It’s also a subclass of LinkageError, which means if this error has occurred then your class will not be loaded into JVM memory. Now let’s take a look at our example program, which upon execution, throwing the following error :

    Exception in thread "main" java.lang.ExceptionInInitializerError
    Caused by: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
            at java.util.ArrayList.rangeCheck(ArrayList.java:635)
            at java.util.ArrayList.get(ArrayList.java:411)
            at StaticInitiazerDemo.<clinit>(StaticInitiazerDemo.java:15)

    By looking at this stack trace, we know that the actual error is java.lang.IndexOutOfBoundsException, which came at line 12 of StaticInitiazerDemo class. It came because of call to get() method of ArrayList with index 0 and come because the size of ArrayList was also zero (Index: 0, Size: 0 part of stack-trace). Now by following this information, you know that our List<CreditCard> is empty when we try to get the first CreditCard from this list.

    import java.util.ArrayList;
    import java.util.List;
    
    /**
     * Java Program to understand and solve ExceptionInitializerError, 
     * which comes
     * When static initializer blocks throws unchecked exception 
     * during class loading
     * and initialization.
     *
     * @author Javin Paul
     */
    
    public class StaticInitializerDemo{
    
        private static final List<CreditCard> cards = new ArrayList<CreditCard>();
        private static CreditCard prefferdCard = cards.get(0); 
        // 1st card is default
        public static boolean isVisa = "VISA".equalsIgnoreCase(
                                             prefferdCard.getNetwork());
    
        public static void main(String args[]) {
    
            makePayment(prefferdCard);
    
        }
    
        public static void makePayment(CreditCard cc) {
            if (isVisa) {
                //offer 5% discount
            }
            // deduct payment
        }
    
    }
    
    class CreditCard {
    
        private long card_number; //16 digit card number
        private int cvv; // 3 digit cvv number
        private int expiryMonth;
        private int expiryYear;
        private String bank;
        private String network;
    
        public CreditCard(long card_number, int cvv, 
                          int expiryMonth, int expiryYear, 
                          String bank, String network) {
            super();
            this.card_number = card_number;
            this.cvv = cvv;
            this.expiryMonth = expiryMonth;
            this.expiryYear = expiryYear;
            this.bank = bank;
            this.network = network;
    
        }
    
        /**
         * @return the card_number
         */
        public final long getCard_number() {
            return card_number;
        }
        /**
         * @return the cvv
         */
        public final int getCvv() {
            return cvv;
        }
        /**
         * @return the expiryMonth
         */
        public final int getExpiryMonth() {
            return expiryMonth;
        }
        /**
         * @return the expiryYear
         */
        public final int getExpiryYear() {
            return expiryYear;
        }
        /**
         * @return the bank
         */
        public final String getBank() {
            return bank;
        }
        /**
         * @return the network
         */
        public final String getNetwork() {
            return network;
        }
    }
    
    Output
    Exception in thread "main" java.lang.ExceptionInInitializerError
    Caused by: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
        at java.util.ArrayList.rangeCheck(Unknown Source)
        at java.util.ArrayList.get(Unknown Source)
        at StaticInitializerDemo.<clinit>(StaticInitializerDemo.java:15)

    Here is a class hierarchy of all Error class in Java. You can see that ExceptionInInitializerError inherit from LinkageError. Its also worth knowing that like RuntimeException, Errors are also unchecked and compiler doesn’t check for mandatory error handling code.

    Exception in thread "main" java.lang.ExceptionInInitializerError fix

    Things to remember:

    1) Remember «Exception in thread «main» java.lang.ExceptionInInitializerError» means Exception has occurred in the main thread, and it is java.lang.ExceptionInInitializerError, which is a subclass of LinkageError and comes when JVM tries to load a class and it failed because of any RuntimeException in static initializer block e.g. IndexOutOfBoundsException or NullPointerException.

    2) Remember that JVM combines all static variable initialization into one static initializer block in the order they appear in the source file. So, don’t think that absence of an explicit static initializer block will not cause this error. In fact, you must ensure the correct order of static variables i.e. if one variable initialization uses another variable then make sure that is initialized first.

    3) Down the line, java.lang.ExceptionInInitializerError can cause ClassNotFoundException or NoClassDefFoundError, if some other code tries to use the class, which caused ExceptionInInitializerError. Why? because loading of that class is failed and it’s not available inside JVM memory. So always check your log files for this before even if you are looking to solve any problem related to class not found.

    4) Remember Static initializer block can throw RuntimeException but not checked Exception because later required mandatory catch block for handling.

    That’s all about «Exception in thread «main» java.lang.ExceptionInInitializerError». We have learned how to troubleshoot this error and find the real culprit, which throwing this error. Always, remember potential side effect of this error is NoClassDefFoundError, which your Java application may throw far from this error, depending upon when other client codes refers to this class in question. So, it’s always better to look for ExceptionInInitializerError, before playing with ClassPath to troubleshoot NoClassDefFoundError in Java.

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

    Public Constructor Summary

    Public Method Summary

    Throwable

    getCause()

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

    Throwable

    getException()

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

    Inherited Method Summary


    From class
    java.lang.Object

    Object

    clone()

    Creates and returns a copy of this Object.

    boolean

    equals(Object obj)

    Compares this instance with the specified object and indicates if they
    are equal.

    void

    finalize()

    Invoked when the garbage collector has detected that this instance is no longer reachable.

    final

    Class<?>

    getClass()

    Returns the unique instance of Class that represents this
    object’s class.

    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
    calling one of the wait() methods) to be woken up.

    final

    void

    notifyAll()

    Causes all threads which are waiting on this object’s monitor (by means
    of calling one of the wait() methods) to be woken up.

    String

    toString()

    Returns a string containing a concise, human-readable description of this
    object.

    final

    void

    wait(long timeout, int nanos)

    Causes the calling thread to wait until another thread calls the notify() or notifyAll() method of this object or until the
    specified timeout expires.

    final

    void

    wait(long timeout)

    Causes the calling thread to wait until another thread calls the notify() or notifyAll() method of this object or until the
    specified timeout expires.

    final

    void

    wait()

    Causes the calling thread to wait until another thread calls the notify() or notifyAll() method of this object.

    Public Constructors


    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.


    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. The detail
    message string is set to null.

    Parameters
    thrown The exception thrown


    public


    ExceptionInInitializerError
    (String s)

    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

    Public Methods


    public

    Throwable

    getCause
    ()

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

    Returns
    • the cause of this error or null if the
      cause is nonexistent or unknown.


    public

    Throwable

    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.

    Returns
    • the saved throwable object of this
      ExceptionInInitializerError, or null
      if this ExceptionInInitializerError has no saved
      throwable object.

    Понравилась статья? Поделить с друзьями:
  • Java lang exceptionininitializererror no error message
  • Java lang exception initialize error
  • Java lang exception idtoken verification error
  • Java lang error что это
  • Java lang error что делать