Java 捕获自定义异常

Java 捕获自定义异常,java,exception,exception-handling,custom-exceptions,Java,Exception,Exception Handling,Custom Exceptions,我的代码有问题。我在这里简化了它: public class SuperDuper { public static void main(String[] args) { try{ method(); } catch(CustomException e) { System.out.println("Caught!"); } } public static voi

我的代码有问题。我在这里简化了它:

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();
    }
}
其中,我的自定义例外是:

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

    public CustomException(String text) {
        super(text);
    }
}
但是,它在编译时返回以下错误:

SuperDuper.java:6: error: unreported exception Exception; must be caught or declared to be thrown
method();
      ^
我做错了什么?如果我将catch更改为Exception,它将工作,否则它将不工作


编辑:我看到此报告是重复的,但站点建议的重复项没有处理此问题。

您声明
method()引发异常
,但您正在捕获
CustomException
。将方法签名更改为
抛出CustomException
。否则,您需要捕获异常,而不是CustomException。

方法()
被声明为抛出
异常
,因此您需要捕获
异常
。您可能是想让
method()
看起来像

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

method()
声明它可以抛出
Exception
,那么在调用它时,您在哪里处理它呢?处理
CustomException
无效。编译器只知道方法引发了
异常
。请读取重复链接。这就解释了答案。投了反对票是因为…?我没有投反对票,但我最终肯定是值得的,因为我投了更高的票,只是为了让它平静下来:)