0

每次我运行此代码时,一切正常,但如果存款方法抛出错误,则只有main 方法中的 捕获异常并打印字符串,catch尽管 catch. ExceptionsDemo为什么会这样?

    public class ExceptionsDemo {
    public static void show() throws IOException {
        var account = new Account();
        try {
            account.deposit(0);//this method might throw an IOException
            account.withDraw(2);
        } catch (InsufficientFundsException e) {
            System.out.println(e.getMessage());
        }
    }
}


    public class Main {
        public static void main(String[] args) {
            try {
                ExceptionsDemo.show();
            } catch (IOException e) {
                System.out.println("An unexpected error occurred");
            }
        }
     }
4

3 回答 3

2

发生这种情况是因为在您的show()方法中,您正在捕获一种特定类型的异常,称为InsufficientFundsException. 但是抛出的异常仅在您的 main 方法中被捕获account.deposit()IOException这就是为什么 main 方法中的 catch 被执行而不是 ExcpetionsDemo 中的 catch

如果你想在你的 ExceptionsDemo 类中捕获 IOException,你可以这样做:

public static void show() {
    var account = new Account();
    try {
        account.deposit(0);//this method might throw an IOException
        account.withDraw(2);
    } catch (InsufficientFundsException e) {
        System.out.println(e.getMessage());
    } catch (IOException e) {
        System.out.println(e.getMessage()); 
    }
}

对于每种类型的异常,单个 try 块可以有多个 catch 块,并且可以通过在每个异常块中对其进行编码来自定义每个异常的处理方式。

于 2021-12-15T06:19:44.863 回答
1

你的 ExceptionsDemo 抛出 a IOException,你的catchinExceptionsDemo 捕获 aInsufficientFundsException所以它不会被捕获ExceptionsDemo,它会冒泡给调用者,并在那里被捕获,前提是有一个catch块来处理所说的异常,它确实如此,否则你会有未捕获的异常。它没有被重新抛出ExceptionsDemo,因为它一开始就没有被抓住

于 2021-12-15T06:16:41.057 回答
-1
try {
    // do what you want
} catch (InsufficientFundsException e) {
    // catch what you want
} catch (Exception e) {
    // catch unexpected errors, if you want (optional)
}
于 2021-12-15T06:26:37.923 回答