What causes and what are the differences between NoClassDefFoundError and ClassNotFoundException?

前端 未结 15 2353
忘了有多久
忘了有多久 2020-11-21 05:27

What is the difference between NoClassDefFoundError and ClassNotFoundException?

What causes them to be thrown? How can they be resolved?

15条回答
  •  感动是毒
    2020-11-21 06:00

    ClassNotFoundException and NoClassDefFoundError occur when a particular class is not found at runtime.However, they occur at different scenarios.

    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.

        public class MainClass
        {
            public static void main(String[] args)
            {
                try
                {
                    Class.forName("oracle.jdbc.driver.OracleDriver");
                }catch (ClassNotFoundException e)
                {
                    e.printStackTrace();
                }
            }
        }
    
    
    
        java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
        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 pack1.MainClass.main(MainClass.java:17)
    

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

        class A
        {
          // some code
        }
        public class B
        {
            public static void main(String[] args)
            {
                A a = new A();
            }
        }
    

    When you compile the above program, two .class files will be generated. One is A.class and another one is B.class. If you remove the A.class file and run the B.class file, Java Runtime System will throw NoClassDefFoundError like below:

        Exception in thread "main" java.lang.NoClassDefFoundError: A
        at MainClass.main(MainClass.java:10)
        Caused by: java.lang.ClassNotFoundException: A
        at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    

提交回复
热议问题