Search code examples
javaexceptioncustom-exceptions

Catching a custom exception


I am having an issue with my code. I have simplified it here:

public class SuperDuper {
    public static void main(String[] args) {        
        try{
            method();
        } catch(CustomException e) {
            System.out.println("Caught!");
        }
    }

    public static void method() throws Exception {
        throw new CustomException();
    }
}

where my custom exception is just:

public class CustomException extends Exception {
    public CustomException() {
        super();
    }

    public CustomException(String text) {
        super(text);
    }
}

However it is returning the following error during compile time:

SuperDuper.java:6: error: unreported exception Exception; must be caught or declared to be thrown
method();
      ^

What is it that I did wrong? If I change the catch to Exception it works, otherwise it does not.

EDIT: I see this got reported as being a duplicate but the duplicates suggested by the site were not dealing with this issue.


Solution

  • You declare that method() throws Exception, but you are catching CustomException. Change your method signature to throws CustomException. Otherwise you'd need to catch Exception, not CustomException.