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); 
    } 
} 

這個節目的輸出拋出ArithmeticExceptionUnsupportedOperationException

記者簡單地問我將如何讓客戶知道提出的原始異常是UnsupportedOperationException型不ArithmeticException的。 我不知道

回答

1

永遠不會返回或拋出一個finally塊。作爲一名面試官,我會期待這個答案。

一個蹩腳的面試官尋找一個小技術細節可能會期望你知道Exception.addSuppressed()。你不能在finally塊中讀取拋出的異常,所以你需要將它存儲在throw塊中以重用它。

所以這樣的事情:

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

相關問題