In this article, we will discuss java.lang.Classnotfoundexception. This ClassNotFoundException is thrown when the classloader can not load the Class from the system. ClassLoader is the class of the JVM core library that is used to load a class or find a class. ClassLoader throws this exception when it fails to load a class from application libraries. JVM uses the following methods to load class files.
1. The forName method from Class class.
2. The loadClass method from ClassLoader class.
3. The findSystemClass method from the ClassLoader class.
Read Also: Difference between ClassNotFoundException and NoClassDefFoundError
1. ClassNotFoundException is a Checked ExceptionClassNotFoundException class inherited from ReflectiveOperationException class which has support of reflection functionalities. Also, ReflectiveOperationException inherited from Exception class. ClassNotFoundException is a checked exception. So we have to throw it from a method declaration or we should catch this exception.
If we execute the following program we will get ClassNotFoundException.
2. Example of the ClassNotFoundException
Though we have not yet included the oracle JDBC driver library to our project it will generate following exception
Exception in thread "main" java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
at java.lang.Class.forName0(Native Method)
We should include the oracle JDBC driver library/jar file to our project to get rid of this kind of exception.
3. How to Deal with ClassNotFoundExceptionIn this part, we should create a new class Employee.java like below code snapshot.
Now in the main method of Test class, we will write below code
If we compile and execute the above Test class it should work.
We know that when we compile the program it will generate .class files to the output directory. For now, we will delete the Employee.class file from the output directory. And then again execute the Test.class file. Now it should generate the following output.
Exception in thread "main" java.lang.NoClassDefFoundError: Employee
Caused by: java.lang.ClassNotFoundException: Employee
Here we can see that it is generating NoClassDefFoundError Exception but the root cause is ClassNotFoundException.To fix this issue we have to again compile the project. Then it should generate proper class files to the output directory. Now, the problem should be solved.
4. NoClassDefFoundError, ClassNotFoundException and UnSupportedClassVersionErrorNoClassDefFoundError – When the java file is present during compile time but it's not available during runtime then this exception should occur.
ClassNotFoundException – When the classloader doesn’t find the class with the provided name, this exception should be thrown.
UnSupportedClassVersionError – When we compiled java files to class files with a java version but during runtime, if we changed the version of java, this exception should occur. When we encounter this error we should check the JAVA_HOME property in the path.