-1

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.

anak
  • 129
  • 8
  • 1
    `method()` declares that it can throw `Exception`, so where are you handling that while calling it? Handling `CustomException` won't work. Compiler only knows about `Exception` being thrown by method. – Rohit Jain Mar 19 '15 at 20:39
  • READ the duplicate link. It explains the answer. – JasonMArcher Mar 20 '15 at 00:03

2 Answers2

2

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.

JNYRanger
  • 6,829
  • 12
  • 53
  • 81
2

method() is declared as throwing Exception, so you need to catch Exception. You probably instead meant method() to look like

    public static void method() throws CustomException {
        throw new CustomException();
    }
dcsohl
  • 7,186
  • 1
  • 26
  • 44