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

前端 未结 15 2390
忘了有多久
忘了有多久 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:04

    Example #1:

    class A{
     void met(){
       Class.forName("com.example.Class1");
     }
    }
    

    If com/example/Class1 doesn't exist in any of the classpaths, then It throws ClassNotFoundException.

    Example #2:

    Class B{
      void met(){
       com.example.Class2 c = new com.example.Class2();
     }
    }
    

    If com/example/Class2 existed while compiling B, but not found while execution, then It throws NoClassDefFoundError.

    Both are run time exceptions.

提交回复
热议问题