NoClassDefFoundError vs. ClassNotFoundException

·

·

Java Developer, we all have seen and felt that situation when we are hitting deadline and we get you see NoClassDefFoundError or sometime ClassNotFoundException. There are also times when we see this situation where local development has no issues and runs great but when deployed to Environments or even High Availability environment such as Production Environment, you get to see NoClassDefFoundError or sometime ClassNotFoundException and now it’s high priority and you want to resolve the issue quickly but you don’t know where to start because it is not happening in your local environment and only in UAT or Production Environment.

Both ClassNotFoundException and NoClassDefFoundError are the cause of classpath issue but there is core difference between them which i am explaining below and also explaining why it might not happen in local development environment but might error out in UAT or Production Environment (High Availability Environment)

ClassNotFoundException

java.lang.ClassNotFoundException is an exception when ClassLoader could not load the class because it couldn’t find in the classpath. For an example, You might get this mostly during use of reflection such as Class.forName(“oracle.jdbc.driver.OracleDriver”); if you don’t have oracleDriver Library Jar in the classpath this case.

NoClassDefFoundError

java.lang.NoClassDefFoundError is an error when ClassLoader finds the class it’s looking for But could not find referencing classes that THIS class needs to complete the operations and that’s because referencing class is not in the classpath. For an example, You might get this mostly during below case:

libStudent.jar
public Class Student{

private String name;
private String grade;
..
..
..
}

libCollege.jar
public Class Campus{

private String campusName;
private Student student;
public Campus()
{
student = new Student();
}

..
..
..
}

libClient.jar
Has libCollege.jar in Classpath but libStudent.jar is not there in classpath
public Class Client{

public static void main(String args[])
{
Campus campus = new Campus();
}

//In This case Campus class was in library but Campus class is referencing Student class and that library is not in the classpath and that is the reason for NoClassDefFoundError

Why not in local development and only when deployed to Environments
When we do local development, we ignore the fact that all the class are compiled and are in classpath because we/our IDE might have settings to use compiled class and not libraries but when we deploy to environment, we reference the Libraries. and as you know Jars are wraped into WAR and WARs are wrapped into EAR file and we should understand that WAR/s file classloader is different from EAR classloader and if we don’t understand this fact you are prone to NoClassDefFoundError only and sometimes java.lang.ClassNotFoundException.

Class Loader Concept In Detail