Pages

Saturday, August 25, 2012

NoClassDefFoundError

This is a very common error which causes headache for most of the beginners when they try to execute their first java program,it compiles without any error, class file is also generated but when you try to run the program 
the most frustrating error pop up,that is:

Exception in thread "main" java.lang.NoClassDefFoundError

Note: don't misunderstand this with ClassNotFoundException,i'll mention the difference between the two similar looking exceptions at the end of this post.


I have faced it a lot of times in the beginning,so i want to share it here
what is the reason behind this error and how to rectify 
here is the reason:
you should know that when we try to run a program like this 
command prompt:/java classname
the JVM searches the classpath to locate the class name you provide to it.
If JVM doesn't find definition of a class in the CLASSPATH which was available at the time of compilation it generates the error 

Exception in thread "main" java.lang.NoClassDefFoundError
So you can easily understand that the problem is not with the code but it is because the JVM is unable to locate the class file,so to rectify the problem you need to :

 >> identify the class which is creating the problem, you can easily find out it from the error message

take an example 

//hello.java
class SayHello
{
 public static void main(String[] args) 
 {
  System.out.println("Hello World!");
 }
}
in the above program there is only one class i.e SayHello after compiling this program 
promt:/javac hello.java
a class "SayHello.class" will be automatically generated. and when you try to run your program from the same directory like this 
prompt:/java SayHello
you get the error Exception in thread "main" java.lang.NoClassDefFoundError
the only reason behind this is you haven't provided the classpath for you class. Provide the class path for you class file and the error will go away automatically.
there are two options 
1> declare the CLASSPATH environment variable 
"Control Panel\System --> advanced system settings -->environment variables"   which sets the classpath permanently. or
2> run your program like this 
prompt:/java -cp . SayHello.java
the -cp argument stands for classpath and "." for the current directory,it tells JVM to look in current directory for the class file. 
this is all you need to do,to get rid of this error.

difference between

ClassNotFoundExceptionNoClassDefFoundError
Occurs when a class is not found which is referenced in the program you are trying to executeOccurs when a class is unavailable to JVM at the time of execution which was there at the time of compilation
Reason may be a missing package or jar file which contains the classonly possible reason is problem with CLASSPATH which is explained above
Problem may be in manifest file which may not have mentioned some jar file which is the source of the class