Java Class Loading Error/ Exception

Have you encountered some class loading/ definition issues in Java recently?
To expedite troubleshooting such issues, you need to be aware of the 3 main Java errors/ exceptions and to be able to differentiate amongst them. They are:
  1. java.lang.ClassNotFoundException
  2. java.lang.NoClassDefFoundError
  3. java.lang.UnsupportedClassVersionError

ClassNotFoundException

Happens when a class cannot be loaded at runtime. This offending class is usually not known a priori
This is often caused by the class loader not being able to dynamically load a required class. Examples of such offending class loaders are
  1. Class.forName()
  2. Classloader.findSystemClass()
  3. Classloader.loadClass()
  4. An IoC container (e.g. Spring)
The exception is thrown with the class that is not found. E.g.
 java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver

To resolve this, check the class against the classpath. The situation would be a lot more complicated when multiple class loaders come into play (E.g. when working with the Java EE containers)

NoClassDefFoundError

Happens when a class that existed at compile time could not be properly loaded at runtime.
The offending class was referenced in code (e.g. instantiated, static methods were called) and existed during compilation but now, could not be properly loaded.

There is a unique case to the NoClassDefFoundError where class initialisation fails.
E.g. java.lang.NoClassDefFoundError: Could not initialize class javax.swing.RepaintManager
This happens when the offending class is found but could not be properly initialised (due to exception/ error in the static initialiser or constructor)

Again in general, the fix could be simply making sure that the classpath contains the class definition. However, in the case of class initialisation failure, the solution would be far more complex.

UnsupportedClassVersionError

Happens when the class was compiled in a higher JDK version but running in a lower one.
To fix this, either:
  1. recompile the offending class/ jar to the lower version, or
  2. upgrade the JRE to the higher version

Comments

Popular posts from this blog

Understanding ITIL Service Management the UML way…

Apache Web Server Troubleshooting