Java.lang.ExceptionInInitializerError

Source: Internet
Author: User

A Error, Reason


Java.lang.ExceptionInInitializerError


Two Reason

The cause of the java.lang.ExceptionInInitializerError error is that there was an error while initializing the class. That is, when the class is loaded, there is an error executing the static property, method block.

Like what

<span style= "Font-family:times New Roman;" >public class aa{   private static AA AA = new AA ();   Private AA () {//constructor Method     init ();   }  public void init () {    ...}} </span>

When the class is initialized, the Init method is called, and if the Init method fails, this type of initialization is unsuccessful and the Java.lang.ExceptionInInitializerError error is reported.

Similarly, in executing

Static{...}


Method block, this error may also be reported.


Three Cause analysis


When an exception occurs in the static initialization block, the JVM throws a Java.lang.ExceptionInInitializerError exception.

Static variables in Java are initialized when the class is loaded. If an exception occurs during initialization of this static variable, an Java.lang.ExceptionInInitializerError exception is thrown.


Any exception can cause this, for example, Java.lang.ArrayIndexOutOfBound or java.lang.NullPointerException. We are usually stunned by this error and feel that we do not define any static initialization blocks, and why we throw exceptionininitializererror exceptions; in fact, Java defaults to the initialization of static variables in a default static initialization block. They are then initialized in the order in which they are declared in the source file. For example, if the variable ABC declaration is used in the first row, in the second row, and in the third row, then the second line of code throws a NullPointerException exception, This exception is encapsulated in a Exceptionininitializererror exception, and if the code executes in the main thread, you will see an error message in the console or in the log file: "Exception in Thread" main " Java.lang.ExceptionInInitializerError ".


In a large system with a large number of log files, such errors are easily overlooked and the programmer gets a Java.lang.NoClassDefFoundError exception. Unfortunately, this error occurs only when other code uses this class, because exceptionininitializererror causes the class to fail to load. Because the class failed to load, the JVM throws Noclassdeffounderror. We'll check the classpath, path, and Java.library.path to see if this class is missing, but we can't find any problems. If you are analyzing the cause of noclassdeffounderror, it is best to look at your log file for Exceptionininitializererror, and then consider whether you want to check for classpath.


Exception in thread "main" java.lang.ExceptionInInitializerError Reason:


As with other errors or exceptions, when you see this line of information, you know that this is a Exceptionininitializererror exception, which is caused by the failure of the static block initialization process during class loading. Since it appears in the main thread responsible for starting the program, you'd better start parsing from the main class, where the main class is the one you specified in the command-line arguments, or the class that you declared the public static void main (String args[]) method. If you look closely at the full stack trace information, you will find the class that raised the Exceptionininitializererror. Exceptionininitializererror is a subclass of Linkageerror, which means that this exception causes your class to fail to load into the JVM's memory. Now let's take a look at this sample program.

<span style= "Font-family:times New Roman;" >importjava.util.ArrayList;importjava.util.List; /** * Java program to understand and Solveexceptioninitializererror, which comes * when static initializer blocks Throwsun Checked exception during class loading * and initialization. * * @author Javin Paul * * Public classstaticinitializerdemo{private static final list<creditcard>cards = new Arra  Ylist<creditcard> (); private static CreditCard Prefferdcard =cards.get (0);   1st card is the 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 cardnumber 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; }} </span>


Output:

<span style= "Font-family:times New Roman;" >exception inthread "main" java.lang.ExceptionInInitializerErrorCaused by:java.lang.IndexOutOfBoundsException: index:0, size:0 at    Java.util.ArrayList.rangeCheck (unknownsource) at    java.util.ArrayList.get (Unknown Source ) atstaticinitializerdemo.<clinit> (staticinitializerdemo.java:15) </span>


Look at the stack trace information and know that the real exception is Java.lang.IndexOutOfBoundsException, which is thrown out in the second line of Staticinitiazerdemo. This is because the get () method of the ArrayList was called and passed in position 0, and the ArrayList size is also 0 (index:0, size:0). After seeing this message you know that when we want to remove the first creditcard from the list, the list is empty.


Four Solutions


Address considerations:

How to solve Exception inthread "main" Java.lang.ExceptionInInitializerError

Here are a few things to keep in mind:

1. "Exception in Thread" main "java.lang.ExceptionInInitializerError" means that the exception appears in the main thread, And is a subclass of Linkageerror Java.lang.ExceptionInInitializerError, which is thrown when the JVM class fails to load, because there is a static initialization code such as indexoutofboundsexception or null Pointerexception such a runtimeexception.


2. Remember that the JVM places the initialization of all static variables into a static initialization block in the order in which they appear in the source file. Therefore, do not assume that this exception does not occur if you do not see the static initial block. In fact, you need to ensure the correct order of static variables, for example, if a variable is initialized with another variable, you have to make sure that the variable is initialized before.


3. If another code wants to use this class, it throws a Exceptionininitializererror exception, which in turn causes classnotfoundexception or Noclassdeffounderror. Why? Because this class fails to load, it is not loaded into the JVM's memory. So if you're solving an exception like a class that doesn't exist, look at the log file for this exception.


4. Remember that static initialization blocks throw runtimeexception instead of checked exceptions, which require a corresponding catch block for processing.


It is necessary to remember that one of the side effects of this anomaly is noclassdeffounderror, The Java program throws this exception in a location that may be far from Java.lang.ExceptionInInitializerError, depending on when the client code refers to the class. Therefore, before looking at the Classpath to resolve noclassdeffounderror exceptions, it is a good idea to check the log for Exceptionininitializererror.


Five Reference URL


1. http://www.2cto.com/kf/201309/241190.html

2. http://www.tuicool.com/articles/IVBVn2

Java.lang.ExceptionInInitializerError

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.