0

このコードを実行するたびに、すべて正常に動作しますが、入金メソッドがエラーをスローした場合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。ただし、によってスローされる例外account.deposit()IOException、メイン メソッドでのみキャッチされます。そのため、メイン メソッドの 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()); 
    }
}

1 つの try ブロックには、例外の種類ごとに複数の catch ブロックを含めることができ、各例外の処理は、各 catch ブロックでコーディングすることにより、必要に応じてカスタマイズできます。

于 2021-12-15T06:19:44.863 に答える
1

あなたの ExceptionsDemo は をスローしIOExceptionます。あなたのcatchinは aExceptionsDemo のみをキャッチするInsufficientFundsExceptionので、 にキャッチされませんExceptionsDemo。呼び出し元にバブリングし、そこでキャッチさcatchれます。キャッチされない例外。ExceptionsDemoそもそもキャッチされていないため、から再スローされていません

于 2021-12-15T06:16:41.057 に答える