捕获自定义异常

Catching a custom exception

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

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() throws Exception,但你正在捕捉CustomException。将您的方法签名更改为 throws CustomException。否则你需要捕获异常,而不是 CustomException。

method()声明为throwingException,所以需要catchException。你可能想让 method() 看起来像

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