3

catch 블록과 finally 블록 모두 Java에서 예외를 throw하면 어떻게됩니까?

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 블록에서 던져진 예외를 실제로 읽을 수 없으므로이를 다시 사용하려면 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

관련 문제