Search code examples
javaclassexceptionclassnotfoundexceptioninitializer

java - ClassNotFoundException when trying to init a class which throws Exception


The source code is following:

public class Main {
    public static void main(String[] args) {
        MyClass mycClass = new MyClass();
    }
}

class MyClass {
    public void foo() throws Exception {
        throw new Exception();
    }
}

Can someone help me understand why MyClass initializer is throwing a ClassNotFoundException but when I remove the throw new Exception() statement from foo function it works.


Solution

  • You declared foo to possibly throw any kind of Exception.

    Any method that could throw a checked exception (and does not catch it) needs to declare this using the throws keyword.

    Your main method calls foo and foo could throw an exception. The main method does not catch that so it would throw the exception to its caller.

    So, the main method needs to have the throws Exception declaration as well.

    The ClassNotFoundException occurs because the main class is not found because it's compilation failed or because it is invalid.

    If you would look at the compiler output, you should see an error telling you that the throws declaration is missing (uncaught exception).