Home Navigation

Saturday 12 September 2020

ClassNotFoundException vs NoClassDefFoundError

ClassNotFoundException and NoClassDefFoundError both are runtime exceptions. They occur when a class not found in the classpath. 

ClassNotFoundException:

It is a checked exception. It happens when a program tries to load a class using the Class.forName() or loadClass() or findSystemClass() method. For example class.forName("oracle.jdbc.driver.OracleDriver") and oracle jdbc driver is not present in the classpath the program will try to load the class and throw the classNotFoundException.

Resolution: Make sure you add the related dependencies in the classpath.

NoClassDefFoundError:

It is a fatal error and happens when jvm can not find the definition of the class by instantiating (new keyword) and load a class with method call. The definition is present at the compile time but missing at runtime.

It usually happens when there is an exception while executing a static block or initializing static fields of the class, so class initialization fails.

Resolution: Sometimes, it can be quite time-consuming to diagnose and fix these two problems. 

  • Make sure whether class or jar containing that class is available in the classpath.
  • If it's available on application's classpath then most probably classpath is getting overridden. To fix that we need to find the exact classpath used by our application
  •  Also, if an application is using multiple class loaders, classes loaded by one classloader may not be available by other class loaders.

Ref: https://www.baeldung.com/java-classnotfoundexception-and-noclassdeffounderror

No comments:

Post a Comment