Java Dailly tip: Why am I getting the NoClassDefFoundError in Java

Java Dailly tip: Why am I getting the NoClassDefFoundError in Java

Problem

I am getting the NoClassDefFoundError error when starting a Java application. What is the usual reason for this?

Solution

While it is possible that this is due to a class path mismatch between compile time and runtime, it is not necessarily true. In this case, it is important to have two or three different exceptions in mind:

  1. java.lang.ClassNotFoundException - this exception indicates that the class was not found in the class path. This indicates that we tried to load a class definition that did not exist in the class path
  2. java.lang.NoClassDefFoundError - this exception indicates that the JVM looked for a class definition in the internal data structure of the class definition and did not find it. This is different than saying it cannot be loaded from the classpath. This usually means we tried to load the class from the classpath before but for some reason it failed - now we are trying to reuse the class (and therefore we have to load it as it failed recently) but "You are not going to even try to load it because We were unable to load it earlier (and I reasonably suspect that we will fail again). The prior failure can be a ClassNotFoundException or ExceptionInitializerError (indicating an error in a static initialization block), or any number of other problems. The point is, NoClassDefFoundError is not necessarily a class path problem.

Let's see an example:

public class SimpleOperation {
    
    static int result = 1/0;
}

public class ExceptionExample {
    
    public static void main(String[] args) {
        try {
            // The following line would throw ExceptionInInitializerError
            SimpleOperation simpleOperation = new SimpleOperation();
        } catch (Throwable t) {
            System.out.println(t);
        }
        // The following line would cause NoClassDefFoundError
        SimpleOperation SimpleOperation = new SimpleOperation();
    }

}

Share this Post