Difference between noclassdeffounderror and classnotfoundexception?

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

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

Example:

ClassNotFoundException: It is a run time exception that is thrown when an application try to load a particular given class by using Class.forName() and loadClass() method and class and jar not present inside the java classpath.
public class ClassNotFoundException {
    public static void main(String[] args) {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

// Exception
java.lang.ClassNotFoundException: com.mysql.driver
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Unknown Source)
    at com.java.ClassNotFoundException.main(ClassNotFoundException.java:6)

Explanation: In the above code, we are trying to load the MySQL driver class and my SQL driver-jar not present inside the classpath then we get  ClassNoteFoundException.
NoClassDefFoundError:  It is an error that is thrown when java try to create of the given class object at runtime but the class definition not present. The require class definition was present at compile-time and missing at runtime.
public class NoClassDefFoundError {
    public static void main(String[] args) {
        Employee e = new Employee();
        e.setName("Ram Sing");
        System.out.println(e.toString());
    }
}

class Employee {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Employee [name=" + name + "]";
    }

}

Exception : If Employee class not present at run time.

    at com.java.NoClassDefFoundError.main(NoClassDefFoundError.java:5)

        
Explanation:  When we compile the above program there us two classes (NoClassDefFoundError.class and Employee.class) generate if we remove Employee.class when we run the application then get the NoClassDefFoundError.

No comments:

Post a Comment