About NewTechnoBuzz
Advertise
Contact Us

Monday, July 14, 2014

What is java.lang.ClassNotFoundException and how to resolve it?

ClassNotFoundException is one the java problem that someday any Java developer faces. java.lang.NoClassDefFoundError and java.lang.ClassNotFoundException are two errors whenever occurs chew up of your precious time while finding and fixing root cause. From its name, it looks like that it is quite a simple exception but underlying cause of it is always different and which classifies it as an environmental issue.

In this tutorial, we'll see:

  • What is ClassNotFoundException?
  • What is root cause of this exception?
  • How to fix it?

Don’t do the mistake that this exception is same like NoClassDefFoundError in Java which is also due to incorrect classpath. Though, both of these exceptions are related to missing class file but they are completely different to each other. Correct understanding of when class is loaded in Java and How Classpath works is must to troubleshoot and fix this error quickly.

What is java.lang.ClassNotFoundException?

As the name suggests, java.lang.ClassNotFoundException is a subclass of java.lang.Exception and comes when Java Virtual Machine (JVM) tries to load a particular class and doesn't find the specified class in classpath. Another important point about this exception is that, it is a checked Exception and you need to provide explicit exception handling while using methods which can possibly throw ClassNotFoundException either by using try-catch block or by using throws clause. Though underlying concept of this exception is simple but it always occurs in such format that you need to spend some time to figure out the root cause of the problem and what exactly wrong with your classpath.

When ClassNotFoundException occurs in Java?

As per the Oracle documentation, ClassNotFoundException comes in following cases:
  • When you try to load a class by using Class.forName() method and class file is not available in classpath.
  • When Classloader try to load a class by using findSystemClass() method.
  • While using ClassLoader.loadClass() method.

If this exception occurs then it means that a java class was not found or could not be loaded at "runtime" from your application current context class loader. This problem can be particularly confusing for Java beginners. This is it is recommended that Java developers must have to learn and refine their knowledge on Java class loaders. Unless you are involved in dynamic class loading and using the Java Reflection API, chances are that the ClassNotFoundException error you are getting is not from your application code but from a referencing API. Another common problem pattern is a wrong packaging of your application code.

Examples of ClassNotFoundException

There can be many scenario where this exception can occur and I am going to discuss one of the scenario.
Scenario
A ClassNotFoundException can happen when you use Java's Reflection capability to dynamically create a class. Below is the example code where I intentionally throw a ClassNotFoundException by trying to create and use a class ("TestClass") that I know doesn't exist:

package com.gsms.test.application;
import java.lang.reflect.Method;

public class ReflectionExampleTest
{
  public ReflectionExampleTest()
  {
    Class clazz;
    try
    {
      clazz = Class.forName("TestClass");
      Method methods[] = clazz.getDeclaredMethods();
      System.out.println(methods[0].toString());
    }
    catch (ClassNotFoundException ex)
    {
      ex.printStackTrace();
    }
  }

  public static void main(String[] args)
  {
    new ReflectionExampleTest();
  }
}

As "TestClass" class doesn't exist, when I try to run the program I get the following Java error message (StackTrace):

java.lang.ClassNotFoundException: TestClass
   at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
   at java.security.AccessController.doPrivileged(Native Method)
   at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
   at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
   at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268)
   at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
   at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
   at java.lang.Class.forName0(Native Method)
   at java.lang.Class.forName(Class.java:164)
   at com.gsms.test.application.ReflectionExampleTest.(ReflectionExampleTest.java:13)
   at com.gsms.test.application.ReflectionExampleTest.main(ReflectionExampleTest.java:26)

How to fix java.lang.ClassNotFoundException in Java?

As you have seen from above examples its clear problem of classpath, so here is my approach to fix or resolve java.lang.ClassNotFoundException:

  • Don’t jump on complex root causes too quickly, rule out the simplest causes first.
  • Review the stack trace and determine which Java class was not loaded properly at runtime e.g. application code, third party API, Java EE container itself etc.
  • Identify the caller e.g. Java class you see from the stack trace just before the Class.forName() or ClassLoader.loadClass() calls.
  • Determine if your application code is not packaged properly e.g. missing JAR file(s) from your classpath
  • Check whether your classpath contains that jar, if your classpath doesn't contain the jar then just add that class in your classpath.

Quick Difference

ClassNotFoundException vs NoClassDefFoundError vs UnSupportedClassVersionError

There are lots of exceptions in java but these three exceptions that gives pain to any developer because these three are mostly related to environment issues and they all depends upon JVM and Classpath behaviour. Though they look similar but there is slight difference between ClassNotFoundException, NoClassDefFoundError and UnSupportedClassVersionError. Below are the differences between these three:
  • ClassNotFoundException comes at runtime when specified class is not available in classpath and mainly due to call to Class.forName(), Classloader.loadClass() or ClassLoader.findSystemClass().
  • NoClassDefFoundError comes when the specified class was present during compilation but are missing at runtime.
  • UnSupportedClassVersionError is easy to differentiate because it’s related to version of classpath and usually comes when you compile your code in higher version of java and try to run on lower version. It can be resolved simply by using one java version for compiling and running your application.

I hope this article helped you to understand and revisit this exception. Please feel free to post any comment or question if you are still struggling with your java.lang.ClassNotFoundException problem.

0 comments