5

特定の例外とその他の例外の 2 つのケースを処理するために、try-catch ブロックを使用したいと考えています。これはできますか?(例)

try{
    Integer.parseInt(args[1])
}

catch (NumberFormatException e){
    // Catch a number format exception and handle the argument as a string      
}

catch (Exception e){
    // Catch all other exceptions and do something else. In this case
    // we may get an IndexOutOfBoundsException.
    // We specifically don't want to handle NumberFormatException here      
}

NumberFormatException は一番下のブロックでも処理されますか?

4

3 に答える 3

11

いいえ、より具体的な例外(NumberFormatException)が最初のキャッチで処理されるためです。キャッシュを交換すると、コンパイルエラーが発生することに注意することが重要です。これは、より一般的な例外の前に、より具体的な例外を指定する必要があるためです。

これはあなたのケースではありませんが、Java 7以降、次のように例外をcatchにグループ化できます。

try {
    // code that can throw exceptions...
} catch ( Exception1 | Exception2 | ExceptionN exc ) {
    // you can handle Exception1, 2 and N in the same way here
} catch ( Exception exc ) {
    // here you handle the rest
}
于 2012-07-18T01:55:39.943 に答える
5

aNumberFormatExceptionがスローされた場合、最初にキャッチされcatch、2番目catchは実行されません。他のすべての例外は2番目に行きます。

于 2012-07-18T01:55:33.243 に答える