All 15 Class Loading & Bytecode Verification questions
More in Class Loading & Bytecode Verification
Advertisement
Java › Class Loading & Bytecode Verification

What causes a ClassNotFoundException versus a NoClassDefFoundError, and how do you distinguish and diagnose each?

Intermediate

Answer

ClassNotFoundException is a checked exception thrown when code explicitly attempts to load a class by name at runtime (via Class.forName(), or a ClassLoader's loadClass()) and that class genuinely cannot be found anywhere on the classpath; NoClassDefFoundError is an Error thrown when a class WAS successfully available and used at compile time, but is missing from the classpath at runtime when the JVM actually attempts to load/link it (commonly caused by a dependency JAR being present at compile-time but accidentally excluded from the runtime classpath/deployment package) -- distinguishing them helps pinpoint whether the issue is a genuinely missing class entirely, or a classpath/packaging mismatch between build-time and run-time environments.
// ClassNotFoundException -- explicit runtime lookup of a class that doesn't exist anywhere
try {
    Class.forName("com.example.NonExistentClass");
} catch (ClassNotFoundException e) {
    // handle: the class genuinely isn't found by name
}

// NoClassDefFoundError -- typically NOT caught explicitly; indicates a packaging/classpath problem
// e.g., a dependency present at compile time but missing from the deployed runtime classpath
Real-world example A team's production deployment throws NoClassDefFoundError for a class that compiled and tested fine locally, traced to a dependency JAR marked with 'provided' scope in Maven that the production server (unlike the developer's local Tomcat instance) didn't actually supply, causing a classpath mismatch only surfacing in that specific environment.

Common follow-ups: Why is NoClassDefFoundError an Error rather than an Exception, and what does that classification imply?;What's the most efficient way to diagnose exactly which JAR/dependency is missing when this occurs?