Home › Java exceptions › ClassNotFoundException
ClassNotFoundException: causes and fixes
A class was requested by name at run time (Class.forName, a driver, a config file) but is not on the classpath.
What it looks like
java.lang.ClassNotFoundException: com.mysql.cj.jdbc.DriverExtends ReflectiveOperationException in java.lang.
What it means
ClassNotFoundException is a checked exception thrown when code loads a class by its name as a string, for example with Class.forName, ClassLoader.loadClass, or a framework that reads a class name from XML or properties. The class loader searched and found nothing. The usual reason is a missing dependency or a typo in the name, and the fix is almost always in the build, not in the code.
Common causes
- A required jar is not in the dependency list, or has
providedortestscope so it is missing at run time. - A typo or an outdated class name in configuration, such as the old MySQL driver class name.
- A fat jar built without all dependencies, or a Tomcat deployment missing a library.
- The class exists but a different class loader is asking (plugins, application servers).
How to fix it
- Run
mvn dependency:treeorgradle dependenciesto confirm the artifact is present with run-time scope. - Check the exact, case-sensitive class name against the library's documentation.
- Rebuild the executable jar and inspect it with
jar tfto see if the class is inside. - In app servers, put the jar where the failing class loader can see it.
Broken and fixed
Class.forName("com.mysql.jdbc.Driver"); // old name, absent in Connector/J 8+Class.forName("com.mysql.cj.jdbc.Driver"); // or omit: JDBC 4 drivers self-register🔎 Unravel the failing code 🔎 Unravel the fix
In Spring and enterprise code
A ClassNotFoundException is about asking by name. If the class was found at compile time and disappeared at run time, you get NoClassDefFoundError instead.
Debug it faster
Paste the whole stack trace into the stack trace beautifier to hide framework frames, jump to the root cause and find the first line of your own code. It runs in your browser, so the trace never leaves your machine.
Frequently asked questions
Is ClassNotFoundException a checked or unchecked exception?
ClassNotFoundException is a checked exception (it extends ReflectiveOperationException), so the compiler forces you to catch it or declare it with throws.
Which package is ClassNotFoundException in?
It lives in java.lang, so the import is import java.lang.ClassNotFoundException; (java.lang needs no import).
What is the first thing to check when I see ClassNotFoundException?
Read the message and the first stack trace line in your own code. The usual causes are: A required jar is not in the dependency list, or has provided or test scope so it is missing at run time; and A typo or an outdated class name in configuration, such as the old MySQL driver class name.