3

Difference between NoClassDefFoundError and ClassNotFoundException in Java

 2 years ago
source link: http://adnjavainterview.blogspot.com/2019/09/difference-between-noclassdeffounderror-classnotfoundexception.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Difference between NoClassDefFoundError and ClassNotFoundException in Java

        Both NoClassDefFoundError and ClassNotFoundException occurs when particular class is not found at run time.They related to java classpath only but occurs different scenario's.

Difference:-

ClassNotFoundException Vs NoClassDefFoundError

1) Java Program to illustrate ClassNotFoundException

    The below code is to throw the ClassNotFoundException because JavaClass class is not found in the classpath.


ClassNotFoundExceptionExample.java

package com.example.demo;

public class ClassNotFoundExceptionExample {
 
         public static void main(String[] args) {
  
                  try {
                       Class.forName("JavaClass");
                  } catch (Exception ex) {
                       ex.printStackTrace();
                  }
         }

}
Output:-
java.lang.ClassNotFoundException: JavaClass
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.example.demo.ClassNotFoundExceptionExample.main(ClassNotFoundExceptionExample.java:8)
2) Program to illustrate NoClassDefFoundError
      For this you don't use any IDE, use command prompt, compile and run separately. In the below code example, created Employee class in the current class. After compilation JVM will create two classes NoClassDefFOundErrorExample.class and Example.class, before run main class delete Example.class and run the main class.
NoClassDefFoundErrorExample.java
package com.example.demo;

public class NoClassDefFOundErrorExample {
 
         public static void main(String[] args) {
                  Example ex = new Example();
                  ex.getNumber();
         }
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK