Member-only story
ClassNotFoundException vs NoClassDefFoundError in Java
🔒 This is a Medium member-only article. If you’re not a Medium member, you can read the full article for free on my blog: Java ClassNotFoundException vs NoClassDefFoundError.
In Java, two commonly confused runtime issues are ClassNotFoundException
and NoClassDefFoundError
. Both are related to class loading issues, but they are very different in their nature, cause, and how they should be handled.
Understanding the distinction between these two is essential when debugging Java applications, especially in large projects with multiple modules, external dependencies, or dynamic class loading.
In this article, we will dive deep into:
- What
ClassNotFoundException
andNoClassDefFoundError
are - Why and when they occur
- Real code examples that trigger them
- Key differences between them
Overview of ClassNotFoundException
- It is a checked exception.
- Belongs to the
java.lang.Exception
class hierarchy. - Occurs when a class is dynamically loaded at runtime (like using
Class.forName()
), but not found in the classpath.
Overview of NoClassDefFoundError
- It is an unchecked error.
- Belongs to the
java.lang.Error
class hierarchy. - Occurs when the JVM fails to load the class definition that was available at compile-time but is missing at runtime.
🔄 Recap with Analogy
Imagine you wrote a letter to a friend:
- If you forgot to write their full name, and the postal service can’t find them — that’s like
ClassNotFoundException
: you tried to reference someone who doesn’t exist at the time of sending. - If you wrote the letter with the correct name, but your friend moved out before delivery, that’s like
NoClassDefFoundError
: they existed when you wrote the letter, but disappeared before receiving it.