ClassNotFoundException Java Example

Java ClassNotFoundException occurs when the application tries to load a class but Classloader is not able to find it in the classpath.
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.
One of the most common examples of ClassNotFoundException is when we try to load JDBC drivers using Class.forName but forget to add it’s jar file in the classpath.

ClassNotFoundException Class Diagram

Java ClassNotFoundException Example

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();
        }
    }
}
Output:
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)
Note that com.javaguides.corejava.Demo doesn’t exist, so When we execute the above program, we get following exception stack trace.

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 class it’s present at runtime.

Reference

Comments