Class Not Found Exception with an example

ClassNotFoundException and NoClassDefFoundError both look similar exception in Java and both are checked exception. On this topic, We are going to discuss the Class Not Found Exception with an example and how to resolve this issue.

Class Not Found Exception with an example:

Class Not Found Exception throws when JVM tries to load a class at runtime from the classpath and specified class is not found in the classpath. This occurs mainly when trying to load classes using Class.forName(), ClassLoader.loadClass() or ClassLoader.findSystemClass(). It is a checked exception. Mostly below cases, we can get class not found an exception in your application.

  • Running application without updating the jar in classpath.
  • This exception also occurs when you have two class loaders and if a ClassLoader tries to access a class which is loaded by another classloader in Java.

Below is the code snippet for the class not found exception example.

Exception stack trace for the above program.

Class Not Found Exception with an example
Class Not Found Exception with an example

 

These are the common exception when we are trying to migrate our application newer jar. Below way we can resolve the above exception.

  • Some cases, class not found exception caused by the third-party jar. To resolve this issue need to update the current version of the jar to the classpath.
  • Class is present in classpath, but the application is overridden with a different classpath. In that case, you must find the exact classpath used by your application.
  • Verify that the name of the requested class is correct and that the appropriate jar exists in your classpath. If not, you must explicitly add it to your application’s classpath.

In this tutorial, We have learned to Class Not Found Exception with an example. In the upcoming article, We will discuss NoClassDefFoundError .

Leave a Reply

Your email address will not be published. Required fields are marked *

Show Buttons
Hide Buttons