ClassNotFoundException Vs. NoClassDefFoundError In Java

May 08, 2022
ClassNotFoundException vs. NoClassDefFoundError In Java



Introduction

Making mistakes and errors is inevitable for a programmer whether you are coding in Java, python or any modern or old programming language. It was always certain that programmers will be making tons of mistakes due to which the concept of errors and exceptions emerged in programming languages. A couple of such exceptions and errors in Java are classnotfoundexception and NoClassDefFoundError, respectively. As the name suggests, the exception is thrown when the class you are trying to use does not exist or cannot be found. Surprisingly, the same is the reason for the occurrence of noclassdeffounderror when the JVM cannot find a requested class on the classpath.

These similarities between them are the main cause of all the confusion, as every new Java developer wonders why they both exist when they both do the same thing. Nevertheless, there are some core differences between both that we will discuss in this post.

explore new Java roles

Error vs Exception

For starters, Errors and Exceptions, both are subclasses of the Throwable Java class. Errors represent the critical conditions that cannot be caught or handled by the code itself, so the programmer will have to make amends to keep the code running otherwise the code will always crash when that error occurs. Whereas Exceptions are the concerning conditions in the code that are raised by the application itself. These can be caught and handled within the code using multiple methods to make sure that ​the application continues to run smoothly without crashing.

ClassNotFoundException

ClassNotFoundException is a checked runtime exception that occurs when a program tries to load a class at runtime using its specified name, but its definition cannot be found in the classpath. Any of these following methods can be used to load the class, 

  • Class.forName() method from class Class
  • loadClass() method from class ClassLoader
  • findSystemClass() method from class ClassLoader

The most common scenario when you would experience this exception is when a Java developer will attempt to connect to a MySQL or Oracle database and the classpath will not have been updated with the required JAR files. 

See this code below, it demonstrates the ClassNotFoundException as the mentioned class “oracle.jdbc.driver.OracleDriver” is not found in the classpath.

1.	public class MyClass
2.	{
3.	    public static void main(String[] args)
4.	    {
5.	   try
6.	        {
7.	            Class.forName("oracle.jdbc.driver.OracleDriver");
8.	        }catch (ClassNotFoundException e)
9.	        {
10.	            e.printStackTrace();
11.	        }
12.	    }
13.	}

If this program is executed without updating the classpath with required JAR files, the following output will be shown on the screen with the exception to output the data in a stack trace:

1.	java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
2.	at java.net.URLClassLoader.findClass(Unknown Source)
3.	at java.lang.ClassLoader.loadClass(Unknown Source)
4.	at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
5.	at java.lang.ClassLoader.loadClass(Unknown Source)
6.	at java.lang.Class.forName0(Native Method)
7.	at java.lang.Class.forName(Unknown Source)
8.	at pack1.MyClass.main(MyClass.java:17) 

NoClassDefFoundError

NoClassDefFoundErroris a fatal error in Java. It occurs when JVM can not find the definition of the class while trying to instantiate a class by using a new keyword or while loading a class with a method call.

The error occurs when a compiler can successfully compile the class, but Java runtime is unable to locate the class file (.class) as if the class definition does not exist or is no longer available. It commonly occurs when there is an error while executing a static block or initializing static fields of the class, both of which result in failure of class initialization.

See this code below:

1.	public class myClass01
2.	{
3.	  Lines of code in this class.
4.	}
5.	public class myClass02
6.	{
7.	    public static void main(String[] args)
8.	    {
9.	        myClass01 obj01 = new myClass01();
10.	    }
11.	}

When this program will be compiled, two class files (.class) will be generated. One of which will be myClass01.class and the other one would be myClass02.class. If you remove the myClass01.class file and try to run the myClass02.class file, Java Runtime System will throw the NoClassDefFoundError. See this output below:

1.	Exception in thread "main" java.lang.NoClassDefFoundError: myClass01
2.	at MainClass.main(MainClass.java:10)
3.	Caused by: java.lang.ClassNotFoundException: myClass01
4.	at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
5.	at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
6.	at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
7.	at java.lang.ClassLoader.loadClass(ClassLoader.java:357)

NoClassDefFoundError vs ClassNotFoundException

This was just the basic description of both classnotfoundexception and NoClassDefFoundError. The question remains, what is the difference between them and why do we require both?

Following are some of the major differences highlighting when each of them can become essential for your code.

· Root Cause

Though both of these are related to missing classes in the classpath, the main difference between them is their root causes. ClassNotFoundExcpetion will be thrown in Java every time an attempt will be made to load a class at run-time using any of the previously mentioned methods and the requested class will not be available.

On the other hand, NoClassDefFoundError is a little different than ClassNotFoundException. In this case, the class would be present during compile time and the application will also compile with no issue and will be linked successfully. However, the classpath will not be available during run-time due to a number of reasons. Most of the time NoClassDefFoundError occurs due to an exception during class initialization when a class that was not loaded successfully was later referenced at the runtime. 

· Explicit vs Implicit Loading of class

There are two basic ways to load a class in Java. You can either do it explicitly which is the most common way or you can go with an implicit way. The ClassNotFoundException will be thrown whenever a class is loaded explicitly by providing the name of the class at runtime while its path is not found. It would not be the case when you load a class implicitly. You will face NoClassDefFoundError when you try to load a class implicitly through a method call from a class and Java runtime will not be able to find its classpath.

· Exception vs Error

We have already covered the difference between exception and Error but it is to be considered that ClassNotFoundException is a checked Exception that is derived directly from java.lang.Exception class. Whenever you are loading a class and want to perform exception handling for ClassNotFoundException you will have to provide an action for its explicit handling. On the other hand, NoClassDefFoundError is an Error derived from Linkage Error so it will be automatically thrown and you will not have any means to prevent it, resulting in the crashing of the program.

· Class Loaders

If you have been using class loaders in Java, you would have encountered a ClassNoFoundException in case of unsuccessfully loading a class. Class loaders are primarily responsible forloading Java classes during runtime. The classes are loaded dynamically to theJava Virtual Machine. Thanks to class loaders, the JVM does not require information about the underlying files or file systems to run Java applications.

A ClassNoFoundException will always be thrown when a class is inaccessible to a class loader. It can be due to a number of reasons. For instance, if you have two or more class loaders in your code and a class loader will try to access a class that is already loaded by another class loader, it will result in a ClassNoFoundException.

How To Resolve ClassNoFoundException And NoClassDefFoundError?

You will eventually encounter a ClassNoFoundException or a NoClassDefFoundError in your code, it is inevitable to avoid them. But you need to know how to properly resolve them. Sometimes it can become quite a tiresome and time-consuming process to identify and correct these two problems. 

Following are a few approaches a developer can consider when dealing with either of these two errors:

  1. You need to make sure at the initial stage that whether the class or jar file containing that class is available in the classpath before you compile the code. If not, always add it first then go for compilation.
  2. If the classpath is available on an application’s classpath then it is most likely that the classpath will get overridden later at some point. To avoid that, you need to first find the exact classpath used by the application and use that in your code.
  3. If class loaders are used by an application in Java, one or multiple classes loaded by a class loader will not be accessible by any other class loaders. As mentioned before, it will result in a ClassNoFoundException despite the correct classpath present. This will be tricky to diagnose if you would not have the required knowledge of class loaders in Java.

See Also: How To Fix An Illegal Start Of Expression In Java

Summary

It was all about ClassNotFoundException vs. NoClassDefFoundError in Java in this article. While both of these exceptions are related to classpath and Java runtime being unable to find a class at run time, it is crucial to be aware of their differences. You need to understand the basic difference between an exception and an error and when you encounter each of them. By knowing the difference, it will get easier to code as well as to debug your Java code. 

new Java jobs

Let’s recap the basic differences:

ClassNotFoundException NoClassDefFoundError
It is a checked Java exception from java.lang.Exception. It is a fatal error in Java present in java.lang.Error.
It occurs when a Java application attempts to load a class at run time that is not updated in the classpath. It occurs when the Java runtime system does not find a class definition, which was available at compile-time, but is either missing or unavailable at run time.
An application itself throws the ClassNotFoundException. It is thrown by the methods that explicitly loads the class using its name like Class.forName(), loadClass() or findSystemClass() method. It is thrown by the Java Runtime System when the class definition is not found at run time.
Developers can handle an exception using a try and catch block or any other method for preventing the program from crashing.

The program will crash whenever NoClassDefFoundError will occur.



author

admin


Candidate signup

Create a free profile and find your next great opportunity.

JOIN NOW

Employer signup

Sign up and find a perfect match for your team.

HIRE NOW

How it works

Xperti vets skilled professionals with its unique talent-matching process.

LET’S EXPLORE

Join our community

Connect and engage with technology enthusiasts.

CONNECT WITH US