3

catchブロックとfinallyブロック例外の両方がJavaでスローされるとどうなりますか?

public class Test_finally { 
    private static int run(int input) { 
     int result = 0; 
     try { 
      result = 3/input; 
     } catch (Exception e) { 
      System.out.println("UnsupportedOperationException"); 
      throw new UnsupportedOperationException("first"); 
     } finally { 
      System.out.println("finally input=" + input); 
      if (0 == input) { 
       System.out.println("ArithmeticException"); 
       throw new ArithmeticException("second"); 
      } 
     } 

     System.out.println("end of method"); 
     return result * 2; 
    } 

    public static void main(String[] args) { 
     int output = Test_finally.run(0); 
     System.out.println(" output=" + output); 
    } 
} 

このプログラムの出力は、私は、クライアントが提起元の例外がタイプUnsupportedOperationExceptionないArithmeticExceptionあった知らせますかArithmeticExceptionないUnsupportedOperationException

インタビュアーは単に尋ねスロー私はインタビューで頼まれたこの質問を考えてみましょう。 私はそれを知らなかった

答えて

1

finallyブロックを戻したり投げたりしないでください。面接官として私はその答えを期待しています。

細かい技術的な細部を探している面倒な面接官は、あなたには、Exception.addSuppressed()が分かると思うかもしれません。 finallyブロックでスローされた例外を実際に読み取ることはできません。スローブロックに格納して再利用する必要があります。

だから、そのような何か:

private static int run(int input) throws Exception { 
    int result = 0; 
    Exception thrownException = null; 
    try { 
     result = 3/input; 
    } catch (Exception e) { 
     System.out.println("UnsupportedOperationException"); 
     thrownException = new UnsupportedOperationException("first"); 
     throw thrownException; 
    } finally { 
     try { 
      System.out.println("finally input=" + input); 
      if (0 == input) { 
       System.out.println("ArithmeticException"); 
       throw new ArithmeticException("second"); 
      } 
     } catch (Exception e) { 
      // Depending on what the more important exception is, 
      // you could also suppress thrownException and always throw e 
      if (thrownException != null){ 
       thrownException.addSuppressed(e); 
      } else { 
       throw e; 
      } 
     } 
    } 

    System.out.println("end of method"); 
    return result * 2; 
} 
+0

一つは、故意 'finally'ブロックから投げないかもしれませんが、様々なものがfinally'ブロック'内で発生する未チェック(予期せぬ)例外を引き起こす可能性があります。 – supercat

関連する問題