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

相关问题