2014-10-14 6 views
4

쉬울 수도 있지만 왜 출력이 1로 오는지 이해할 수 없습니다. 4. 9 행의 return 문의 기능은 무엇입니까?왜 그런 결과가 나오나요?

public static void main(String[] args) { 
    try{ 
     f(); 
    } catch(InterruptedException e){ 
     System.out.println("1"); 
     throw new RuntimeException(); 
    } catch(RuntimeException e){ 
     System.out.println("2"); 
     return;     \\ Line 9 
    } catch(Exception e){ 
     System.out.println("3"); 
    } finally{ 
     System.out.println("4"); 
    } 
     System.out.println("5"); 
} 
     static void f() throws InterruptedException{ 
      throw new InterruptedException("Interrupted"); 
    } 

미리 감사드립니다.

+0

'try'가없고 9 행이 실행되지 않아 런타임 예외가 catch되지 않습니다. – Narmer

+0

또한'RuntimeException'은 검사되지 않은 예외이기 때문에 5가 인쇄되지 않을 것이므로 내부적으로 (try-catch 블록이 없으면) catch되고'System.out.println ("5"); 앞에 프로그램이 종료됩니다. – Narmer

답변

2

당신의 function f()InterruptedException을 던졌습니다 끝에서 호출됩니다 , 첫 번째 catch 블록에 걸리므로 (따라서 1을 인쇄합니다.)이 catch 블록은 다른 예외를 throw 할 수 없습니다 (메서드에 의해 throw되지 않는 경우). 따라서 no 다른 catch 블록은 사용자의 예외를 포착 할 수 있으므로 마침내 실행됩니다 (마침내 바보 같은 무한 루프 사례를 제외하고 모든 경우에 실행됩니다). Exception thrown inside catch block - will it be caught again?을 참조 할 수 있습니다.

도움이되기를 바랍니다.

그냥 요약하면 try 블록 &에서 예외를 throw 할 수 있습니다 (좋은 catch 블록이있는 경우). 그러나 catch 블록을 사용하면 메소드가 throw하는 예외 만 throw (및 결과적으로 catch) 될 수 있습니다.

catch 블록에서 예외를 throw하는 경우 메서드에 의해 throw되지 않는 것은 의미가 적어서 catch되지 않습니다 (예 : 해당 경우). F로

1

당신이 f()이 예외 : InterruptedException 던져 볼 수 있으므로 먼저 첫 번째 catch 블록 내부에 다음 마침내 그것이 4 인쇄 할 수 있도록 실행됩니다 1를 인쇄 할 수있다.

1

f()이 InterruptedException을 throw하기 때문에 1이 인쇄됩니다. 예외는 첫 번째 catch 블록에서 처리되므로 더 이상 다른 예외 블록에서 처리되지 않습니다. finally 문은 항상 실행되므로 4도 함께 인쇄됩니다.

1
try{ 
    f(); 
} catch(InterruptedException e){ 
    System.out.println("1"); 
    throw new RuntimeException(); // this RuntimeException will not catch by 
            //following catch block 
} catch(RuntimeException e){ 

코드를 변경하려면 다음과 같이 코드를 변경해야합니다.

try{ 
     f(); 
    } catch(InterruptedException e){ 
     System.out.println("1"); 
     try { 
      throw new RuntimeException();// this RuntimeException will catch 
             // by the following catch 
     }catch (RuntimeException e1){ 
      System.out.println("hello"); 
     } 
    } catch(RuntimeException e){ 
     System.out.println("2"); 
     return; 
    } catch(Exception e){ 
     System.out.println("3"); 
    } finally{ 
     System.out.println("4"); 
    } 
    System.out.println("5"); 

는 그런 다음 아웃

1 
    hello // caught the RunTimeException 
    4 // will give you 2,but also going to finally block then top element of stack is 4 
    5 // last print element out side try-catch-finally 
1

f()InterruptedException 그래서 당신이 1을 얻을 던져 "넣어. 당신이 얻을 수 있도록 마지막 항상 4.

1

()는 실행 예외 : InterruptedException,

catch(InterruptedException e){ 
     System.out.println("1"); 
     throw new RuntimeException(); 
} 
던져

인쇄 ->1

마지막 프로그램을 종료하기 전에 실행 도착

,

finally{ 
     System.out.println("4"); 
} 

인쇄 - >

리턴 코드는 실행되지 않지만 마침내 실행됩니다.

관련 문제