ClassNotFoundException in Java with Examples

In this post, we will learn what is ClassNotFoundException in Java, common causes, practical examples, how to handle it, and best practices.

What is ClassNotFoundException? 

The ClassNotFoundException is a checked exception that signals the Java Runtime Environment (JRE) cannot find the specified class in its classpath during runtime. It's important to note that this is different from the NoClassDefFoundError, which occurs when the class was available during compile-time but not at runtime. 

Common Causes

Missing JAR: The class might be present in a JAR file that's not in the runtime classpath.

Misconfigured Build Tools: Build tools like Maven or Gradle might not have properly packaged the class or included necessary dependencies. 

Dynamic Class Loading: Using reflection to load classes can cause this if the class is not available.

JDBC Drivers: Historically, one of the most common examples of ClassNotFoundException is when we try to load JDBC drivers using Class.forName but forget to add its jar file in the classpath.

ClassNotFoundException Class Diagram

Java ClassNotFoundException Example #1

The below example demonstrates the common causes of java.lang.ClassNotFoundException is using Class.forName or ClassLoader.loadClass to load a class by passing the string name of a class and it’s not found on the classpath.
package com.javaguides.corejava;

public class ClassNotFoundExceptionExample {

    public static void main(String[] args) {

        try {

            Class.forName("com.javaguides.corejava.Demo");

            ClassLoader.getSystemClassLoader().loadClass("com.javaguides.corejava.Demo");

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
Note that com.javaguides.corejava.Demo doesn’t exist, so When we execute the above program, we get the following exception stack trace.
java.lang.ClassNotFoundException: com.javaguides.corejava.Demo
 at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
 at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
 at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
 at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
 at java.lang.Class.forName0(Native Method)
 at java.lang.Class.forName(Class.java:264)
 at com.javaguides.corejava.ClassNotFoundExceptionExample.main(ClassNotFoundExceptionExample.java:9)
How to fix this exception: It’s very easy to fix ClassNotFoundException because the exception stack trace clearly specifies the class not found. Just check for classpath settings and make sure the class it’s present at runtime.

Java ClassNotFoundException Example #2

Let's demonstrate this exception using reflection to load a class dynamically:
public class ClassNotFoundExceptionExample {
    public static void main(String[] args) {
        try {
            Class<?> loadedClass = Class.forName("com.missing.MyMissingClass");
            System.out.println("Class loaded successfully: " + loadedClass.getName());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
In the example above, we're trying to load a class named com.missing.MyMissingClass using the Class.forName() method. Since this class is fictional and doesn't exist in our classpath, executing the program will throw a ClassNotFoundException. Output:
java.lang.ClassNotFoundException: com.missing.MyMissingClass
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:352)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at ClassNotFoundExceptionExample.main(ClassNotFoundExceptionExample.java:5)

How to Handle ClassNotFoundException? 

Check Dependencies: Ensure all required JARs or dependencies are added to the classpath. 

Review Build Configuration: Ensure your build tools are correctly configured to include all necessary classes and dependencies. 

Be Cautious with Reflection: If using dynamic class loading, ensure proper error handling mechanisms are in place. 

Update IDE Settings: Sometimes, IDE settings might cause discrepancies between build time and runtime. Keep an eye on those configurations. 

Best Practices

Prefer using dependency management tools like Maven or Gradle. They manage the classpath efficiently and reduce potential issues. 

Avoid using reflection unnecessarily. If you must, always include thorough error handling. 

Periodically clean and rebuild your project to ensure a consistent state. 

Conclusion 

In this post, we have learned what is ClassNotFoundException in Java, common causes, practical examples, how to handle it, and best practices. Happy coding!

Comments