Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
User-Defined Custom Exception in Java
Next article icon

ClassNotFoundException Vs NoClassDefFoundError in Java

Last Updated : 10 Nov, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Both of the exceptions that are ClassNotFoundException and NoClassDefFoundError occur when the class is not found at runtime. They are related to the Java classpath. 

ClassNotFoundException

ClassNotFoundException occurs when you try to load a class at runtime using Class.forName() or loadClass() methods and requested classes are not found in classpath. Most of the time this exception will occur when you try to run an application without updating the classpath with JAR files. This exception is a checked Exception derived from java.lang.Exception class and you need to provide explicit handling for it. This exception also occurs when you have two class loaders and if a ClassLoader tries to access a class that is loaded by another classloader in Java. You must be wondering that what actually is classloader in Java. Java ClassLoader is a part of the Java Runtime Environment that dynamically loads Java classes in JVM(Java Virtual Machine). The Java Runtime System does not need to know about files and files systems because of classloaders. 

Example

Java




// Java Program to Illustrate ClassNotFoundException
public class GFG {
 
    // Main driver method
    public static void main(String args[])
    {
 
        // Try block to check for exceptions
        try {
 
            Class.forName("GeeksForGeeks");
        }
 
        // Catch block to handle exceptions
        catch (ClassNotFoundException ex) {
 
            // Displaying exceptions on console along with
            // line number using printStackTrace() method
            ex.printStackTrace();
        }
    }
}
 
 

Output:

ClassNotFoundException is raised in the above program as class “GeeksForGeeks” is not found in the classpath.

NoClassDefFoundError

Now dwelling on the next exception that is NoClassDefFoundError occurs when the class was present during compile time and the program was compiled and linked successfully but the class was not present during runtime. It is an error that is derived from LinkageError. Linkage error occurs when a class has some dependencies on another class and the latter class changes after compilation of the former class. NoClassFoundError is the result of implicit loading of class because of calling a method or accessing a variable from that class. This error is more difficult to debug and find the reason why this error occurred. So in this case you should always check the classes which are dependent on this class. In order to illustrate let us first make any two classes for a java program and link them. 

Example

Java




// Java Program to Illustrate NoClassDefFoundError Exception
 
// Class 1
// Helper class
class GeeksForGeeks {
 
    // Method
    void greeting()
    {
        // Print statement whenever method is called
        System.out.println("hello!");
    }
}
 
// Class 2
// Main class
class GFG {
 
    // Main driver method
    public static void main(String args[])
    {
        // Creating object of class 1
        // inside main() in class2
        GeeksForGeeks geeks = new GeeksForGeeks();
 
        // Calling method of above class
        geeks.greeting();
    }
}
 
 
Output
hello!

Output explanation: 

Above program will be successfully compiled and generated two classes ‘GeeksForGeeks.class’ and ‘GFG.class.’ Now remove GeeksForGeeks.class file and run GFG.class when we saw that at Java runtime NoClassDefFoundError will be thrown.

ClassNotFoundException Vs NoClassDefFoundError

  • As the name suggests, ClassNotFoundException is an exception while NoClassDefFoundError is an error.
  • ClassNotFoundException occurs when classpath does not get updated with required JAR files while error occurs when the required class definition is not present at runtime.


Next Article
User-Defined Custom Exception in Java

N

NishuAggarwal
Improve
Article Tags :
  • Difference Between
  • Java
  • Java-Exceptions
Practice Tags :
  • Java

Similar Reads

  • How to Solve java.lang.ClassNotFoundException in Java?
    In Java, java.lang.ClassNotFoundException is a checked exception and occurs when the Java Virtual Machine (JVM) tries to load a particular class and the specified class cannot be found in the classpath. ClassNotFoundException should be handled with a try-catch block or using the throw keyword. In ol
    4 min read
  • User-Defined Custom Exception in Java
    In Java, an Exception is an issue (run-time error) that occurs during the execution of a program. When an exception occurs, the program terminates abruptly, and the code beyond the exception never gets executed. Java provides us the facility to create our own exceptions by extending the Exception cl
    4 min read
  • Method Class | getExceptionTypes() Method in Java
    The java.lang.reflect.Method.getExceptionTypes() method of "Method class" returns an array of Exception Type Class Objects declared to be thrown by the method object to handle exception inside the method. All the exceptions handled by method using thrown clause, are returned as array of Class object
    3 min read
  • Method Class | getGenericExceptionTypes() Method in Java
    The getGenericExceptionTypes() method of java.lang.reflectMethod class returns an array of Type objects representing Exceptions thrown by the method object to handle exception. All the exceptions handled by method using thrown clause are returned as array of Type objects using this method. This meth
    4 min read
  • Null Pointer Exception in Java
    A NullPointerException in Java is a RuntimeException. In Java, a special null value can be assigned to an object reference. NullPointerException is thrown when a program attempts to use an object reference that has the null value. Example: [GFGTABS] Java // Demonstration of NullPointerException in J
    5 min read
  • How to Solve Class Cast Exceptions in Java?
    An unexcepted, unwanted event that disturbed the normal flow of a program is called Exception. Most of the time exceptions are caused by our program and these are recoverable. Example: If our program requirement is to read data from the remote file locating at the U.S.A. At runtime, if the remote fi
    3 min read
  • How to Fix java.lang.classcastexception in Java?
    ClassCastException in Java occurs when we try to convert the data type of entry into another. This is related to the type conversion feature and data type conversion is successful only where a class extends a parent class and the child class is cast to its parent class. Here we can consider parent c
    6 min read
  • Errors V/s Exceptions In Java
    In Java, errors and exceptions are both types of throwable objects, but they represent different types of problems that can occur during the execution of a program. Errors are usually caused by serious problems that are outside the control of the program, such as running out of memory or a system cr
    5 min read
  • Java Checked vs Unchecked Exceptions
    In Java, Exceptions is an unwanted or unexpected event that occurs during the execution of a program, i.e., at run time, that disrupts the normal flow of the program’s instructions. In Java, there are two types of exceptions: Checked Exception: These exceptions are checked at compile time, forcing t
    5 min read
  • Exception Propagation in Java
    In Java, an exception is first thrown from the top of the stack, and if it is not caught, it drops down the call stack to the previous method. After a method throws an exception, the runtime system attempts to find something to handle it. The set of possible "somethings" to handle the exception is t
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences