Search code examples
javaexceptionthrowchecked-exceptions

Throwing exceptions outside of a method - Java


I am a beginner in Java.

I declared a method as public void method() throws Exception, but whenever I try to call that method in another area of the same class by using method();, I get an error:

Error: unreported exception java.lang.Exception; must be caught or declared to be thrown

How can I use that method without getting this error?


Solution

  • In the other method that calls method(), you will have to somehow handle the exception that method() is throwing. At some point, it either needs to be caught, or declared all the way up to the main() method that started the whole program. So, either catch the exception:

    try {
        method();
    } catch (Exception e) {
        // Do what you want to do whenever method() fails
    }
    

    or declare it in your other method:

    public void otherMethod() throws Exception {
        method();
    }