by BehindJava
What is java.lang.ClassNotFoundException in Java and How to resolve it
In this blog, we are going to learn about what is ClassNotFoundException and its resolution.
ClassNotFoundException
- This exception is thrown when an application tries to load any class at runtime using class.forName or loadClass() or findSystemClass() methods.
- loadClass() and findSystemClass() methods are from the class loader class. So when the specified class is not found in the class path this exception is thrown.
- This exception also occurs when you have two class loaders. If a class loader tries to access a class that is loaded by another class loader in Java.
Example: Lets say, we have a class where we specified the database jar name in the Class.forName. But intentionally we didn’t update the class path with the required JAR. In this case we get the ClassNotFoundException error as shown below.
public class BehindJava {
public static void main(String[] args) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:636)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:182)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:519)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:375)
at ds.BehindJava.main(BehindJava.java:8)