Add to Google Reader or Homepage

java.lang.exceptionininitializererror


ExceptionInInitializerError:


       In this post i am going to discuss about the Exception In Initialize Error.This java exception belongs to the java.lang. package.This exception extends the Linkage Error.On seeing this exception you might have no idea about the exception as i have confused.

What is Exception In Initialize Error?

On seeing the name of the exception you may be able to guess that this exception is related to initialization of a variable.Yes of course this error is related to the initialization of a static variables.The variable may be of primitive type or user defined type.You might all have known about the static initializer of a class.
A static initializer is a block enclosed within curly braces without having any name and return type except having the keyword static as follows

static
{
//initialization of values;
}

The static initializer block is meant for initializing the static variables.

Why this ExceptionInInitializer Error is thrown?

If any error occurs during the initialization of variables inside the static initializer block of a class then this error would be thrown.Thus we have to understand that this exception is thrown ,when other exceptions arise in the static initializer block.In the error message the original cause for this exception  is also shown.

How to fix this exception?

Since this exception arises in consequence of some other exceptions that arises in the static initializer block.
We have to ensure that the original cause of this exception is fixed otherwise we cannot be able to deal with this exception in any way.

Example situations of this exception:

import java.io.*;
import java.lang.*;

class Exin
{
private static String name;
private static char c;
public Exin(String n)
{
name=n;
}
static
{
c=name.charAt(12);
}
}

public class Exin1
{
public static void main(String args[])
{
Exin e=new Exin("ganesh");

}
}


Exception thrown:


Exception in thread "main" java.lang.ExceptionInInitializerError
        at Exin1.main(Exin1.java:22)
Caused by: java.lang.NullPointerException
        at Exin.(Exin1.java:14)
        ... 1 more

Note that in the above program i have tried to access the 12th character in the string "ganesh" using the method charAt() which causes null pointer exception thereby causing the ExceptionInInitializer error.

5 comments:

Gn said...

excellent

Pavithra Shenoy said...

Informative!

Unknown said...

Thank you very much l always lookfor such explanation about any topic.simple and effective

Jeremy Levett said...

thanks

Unknown said...

Nice and understandable article

Post a Comment

 
java errors and exceptions © 2010 | Designed by Chica Blogger | Back to top