ClassNotFoundException vs NoClassDefFoundError in java

ClassNotFoundException

ClassNotFoundException is an exception that occurs when we try to load a class at run time using Class.forName() or loadClass() methods and mentioned classes are not found in the classpath.

public class Main { 
 
	public static void main(String[] args) 
	{ 
		try {
            Class myClass = Class.forName("test.MyTest");
            System.out.println("Class " + myClass + " found in test package.");
        }
        catch (ClassNotFoundException e) {
            System.out.println("A ClassNotFoundException was caught: " + e.getMessage());
            e.printStackTrace();
        }
	} 
}

Output

A ClassNotFoundException was caught: test.MyTest 
java.lang.ClassNotFoundException: test.MyTest  
        at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Class.java:264) 
        at Main.main(Main.java:6)

Note:

  • ClassNotFoundException will not occur at compile time, it always occur at run-time because we are loading Class.forName or ClassLoader.loadClass, and compiler will have no idea if the specified class is present or not.
  • ClassNotFoundException is checked exception and that’s why we have to handle it using try, catch or finally keywords, otherwise it will give compile time exception.
public class Main { 
 
	public static void main(String[] args) 
	{ 
		 Class myClass = Class.forName("test.MyTest");
         System.out.println("Class " + myClass + " found in test package.");
	} 
}

Output

Main.java:5: error: unreported exception ClassNotFoundException; must be caught or declared to be thrown
		 Class myClass = Class.forName("test.MyTest");
		                              ^
1 error

NoClassDefFoundError

NoClassDefFoundError is an error that occurs when a particular class is present at compile time, but was missing at run time.

Note: It always occur at run-time.

class Test
{
  // Test class code
}
public class Main
{
    public static void main(String[] args)
    {
        Test test = new Test();
    }
}

When we compile the above program, two classes will be created. Test.class and Main.class. Now, move Test.class into some other folder and try to execute the program.

Output

Exception in thread "main" java.lang.NoClassDefFoundError: Test
at MainClass.main(MainClass.java:9)
Caused by: java.lang.ClassNotFoundException: Test
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)

Java interview questions on Exception Handling