Wednesday, 16 March 2016

NoClassDefFoundError in Java

java.lang.Object à  java.lang.Throwable à java.lang.Error à java.lang.LinkageError à java.lang.NoClassDefFoundError

public class NoClassDefFoundError extends LinkageError

When a class is present during compile time but at run time the classes are changed or removed or class's static initializes threw exceptions.

Scenario that when I faced NoClassDefFoundError

Due to Exception in Static Initializer
If we get any runtime exception while executing static initializer (static block or static variable declaration executes while load the class) and JVM class loader will not able to load class due ExceptionInInitializerError throws by static initializer, which will leads to NoclassDefFoundError.

class DivideClass {
     /**Here ArithmeticException will lead to
      * ExceptionInInitializerError which will lead to
      * NoClassDefFoundError
      */
     static {
           int undefined = 1 / 0;
     }
     public String method() {
           return "from divide class";
     }
}

public class TestException {
     public static void main(String[] args) {
           DivideClass d = new DivideClass();
     }
}

How to deal with the NoClassDefFoundError?
1. Verify that all required Java classes are included in the application’s classpath. The most common mistake is not to include all the necessary classes, before starting to execute a Java application that has dependencies on some external libraries.

2. The classpath of the application is correct, but the Classpath environment variable is overridden before the application’s execution.

3. Verify that the aforementioned ExceptionInInitializerError does not appear in the stack trace of your application.

4. Check that there should not any runtime exception while loading the Class. 


Related Post:
ExceptionInInitializerError in Java



No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...