Friday, November 6, 2015

java.lang.NoClassDefFoundError vs ClassNotFoundException

There is common missunderstanding between java.lang.NoClassDefFoundError & java.lang.ClassNotFoundException


Both seems to be same and most of us consider both as due to required class file not available in the class path.

If so, certainly java no need both, then why java have both?

If we look closely we can easily find a quick difference.

Yes! As we guessed one is Error & other one is Exception.

So what? What else?

Let me brief with below code.

Just try below code; it will be interesting to understand behavior of both scenarios.

public class ClassDefExceptionTest {
       static {
              ClassDefExceptionTest.init();
       }
       public ClassDefExceptionTest(){
             
       }
       private static void init(){
              //
              //Some useful code
              //
              throw new RuntimeException("Sorry you can't create this object");
       }
      
}

public class TestFun {
       public static void main(String a[]){
              ClassDefExceptionTest test = null;
              try{
               test = new ClassDefExceptionTest();
              }catch(Throwable e){
                    
                     e.printStackTrace();
              }
              
              try{
                      test = new ClassDefExceptionTest();
                      
              }catch(Throwable e){
                           e.printStackTrace();
              }
               

              try{
                 Class ctest = Class.forName("fhd.practise.ClassDefExceptionTest");
                 System.out.println("loaded successfully.."+ctest.getSimpleName());

                 ClassDefExceptionTest tobj = (ClassDefExceptionTest)ctest.newInstance();
                 System.out.println("Instance created successfully..");
              }catch(Throwable e){
                           e.printStackTrace();
              }
                  
         
     try{
              Class ctest = Class.forName("fhd.practise.ClassNoWhereAvailable");
           }catch(Throwable e){
                     e.printStackTrace();
                        }
  
       }
}



Any guess on output?

No yet guessed? Then please test above code and see :-)


java.lang.NoClassDefFoundError in web application most often developers get treat this error wrongly, as root cause java.lang.ExceptionInInitializerError generated long back and may scrolled up in the log. So developer assume particular class not reachable and waste time running behind it, we can’t blame developers just googlers, Since Googling mislead us as below.

NoClassDefFoundError means that the class is present in the classpath at Compile time, but it doesn't exist in the classpath at Runtime.

This is true in some scenario but not always.

NoClassDefFoundError can occur for multiple reasons like

•             ClassNotFoundException -- .class not found for that referenced class irrespective of whether it is available at compile time or not (i.e base/child class).
•             ExceptionInInitializerError -- Class file located, but Exception raised while initializing static variables or static blocks
•             ClassLoaders also may cause such error, which is basically ClassNotFoundException, in this scenario class may present in classpath but attempt to load from different ClassLoader

In a nut shell, when we face java.lang.NoClassDefFoundError follow the below 3 steps.


1.   Identify rout cause of such error by just scrolling above the logs and verify root cause is java.lang.ExceptionInInitializerError OR java.lang.ClassNotFoundException
Some scenario it is not possible to find none of the above as the server may start long back and logs got rotated from the system or it will be tedious task to go through tens of log files.

2.     Then next approach is locate the candidate class from the class path, if not available in anywhere in the class path then solution is simple, get required class or jar and add it to the class path :-)
Most of us wonder if particular class is available in the class path, what is wrong………….

Nothing!

Simply pay attention on static block/variable of particular class, definitely something wrong will be going on static block/variable 

3.     If above couldn’t help, Issue related will be with ClassLoader, which is basically ClassNotFoundException, in this scenario class may present in classpath but attempt to load from different ClassLoader. Which is also simple to fix but we should have clear idea about classloaders, let me explain it in the another blog