-
Notifications
You must be signed in to change notification settings - Fork 4
Java ClassNotFoundException Class with 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 are using Class.forName or ClassLoader.loadClass to load a class by passing 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.
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 above program, we get following exception stack trace.