BackendBench
Coffee

Home › Java exceptions › ClassNotFoundException

Checked exception · java.lang

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.Driver

Extends 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

How to fix it

  1. Run mvn dependency:tree or gradle dependencies to confirm the artifact is present with run-time scope.
  2. Check the exact, case-sensitive class name against the library's documentation.
  3. Rebuild the executable jar and inspect it with jar tf to see if the class is inside.
  4. In app servers, put the jar where the failing class loader can see it.

Broken and fixed

fails
Class.forName("com.mysql.jdbc.Driver"); // old name, absent in Connector/J 8+
works
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.

Related exceptions

More tools you might need