Thursday, August 16, 2012

Cause of Error and Exception occur at Runtime in Java

1)java.lang.UnsupportedClassVersionError
This exception occur when you compile the java class with higher version of java environment and try to run that class file in lower version of java environment
for example if you compile the java class with java6 and try to  run that class with java5 you faced this type of exception

2)java.lang.NoClassDefFoundError
This exception occurs when Java Virtual Machine is not able to find a particular class at runtime which was available during compile time.
possibility of this:
a) Class is not available in Java Classpath.
b) You might be running your program using jar command and class was not defined in manifest file's ClassPath attribute.
c) Any start-up script is overriding Classpath environment variable.
d) Because NoClassDefFoundError is a sub class of java.lang.LinkageError it can also come if one of it dependency like native library may not available.
e) Check for java.lang.ExceptionInInitializerError in your log file. NoClassDefFoundError due to failure of static initialization is quite common.
f) If you are working in J2EE environment than visibility of Class among multiple Classloaders can also cause java.lang.NoClassDefFoundError, see examples and scenario section for detailed discussion.

3)java.lang.ClassNotFoundException
This exception is nor similair with java.lang.NoClassDefFoundError because ClassNotFoundException comes when JVM tries to load a class at runtime dynamically means you give the name of class at runtime and then JVM tries to load it and if that class is not found in classpath it throws
java.lang.ClassNotFoundException. While in case of NoClassDefFoundError the problematic class was present during Compile time and that's why program was successfully compile but not available during runtime by any reason.

4)java.lang.ClassCastException
This exception occur when we attempted to cast an object to a subclass of which it is not an instance. For example, the following code generates a ClassCastException:
         Object x = new Integer(0);
         System.out.println((String)x);

5)java.lang.ArrayIndexOutOfBoundsException
This exception occur when we accessed the array with an illegal index. The index is either negative or greater than or equal to the size of the array.
we always have to remember that The array indexes in Java start from 0 and go to array.length - 1

6)java.lang.NullPointerException
This exception is most common and every developer faced this exception once in there life.This exception occur when you performed any operation for null object.
To avoid this kind of exception check the null condition before performing any operation of object
for example
String s=null;//here s  is null at present and now if we preform
s.toString();//here you faced NullPointerException

always check null like
if(s!=null)
{
s.toString();
}
 

If you really enjoyed this
give feedback
thanks...... :)