ClassNotFoundException vs NoClassDefFoundError

ClassNotFoundException and NoClassDefFoundError occur when a required class is not found in the classpath at runtime.

In this tutorial, we resolve the conflict between these 2 exceptions and explain the different scenarios of reproducing each one of them.

1- ClassNotFoundException

As per java doc, this exception is thrown when trying to instantiate a class using one of these methods: forName(), findSystemClass(), loadClass() but the class definition doesn’t exist in the classpath.

A common scenario for reproducing this exception is to load the oracle driver before opening a connection to an oracle database:

It’s worth to mention that ClassNotFoundException is a checked exception, which means that eclipse or any other IDE would ask the developer to handle it explicitly at compile time.

2- NoClassDefFoundError

This error is thrown when an application tries to use a class using new operation or through a static call but the class definition doesn’t exist in the classpath.

Ideally, IDE wouldn’t compile an application if a specific class is not found in the classpath. So this error means that the requested class was found during the compile time but missed at runtime.

Common scenarios:

  • Your application uses a class A which doesn’t exist in the classpath.
  • Your application uses a jar which implicitly uses a class A and class A doesn’t exist in the classpath.
  • Your application uses a jar called A.jar which implicitly uses another jar called B.jar and B.jar doesn’t exist in your application’s classpath.

It’s worth to mention that this exception is not checked and can’t be handled at compile time.

In short, both errors imply that some class is not found in the classpath and normally the missing class is displayed along with the exception stacktrace. So in order to resolve the exception, you should add the missing class or jar to your application’s classpath.

 

Hussein Terek

Founder of programmergate.com, I have a passion in software engineering and everything related to java environment.

You may also like...

Leave a Reply

avatar