2016-02-14 15 views
0

爲什麼此代碼不打印「d」。爲什麼它不會進入RunTimeException的catch塊?異常鏈如何在我的代碼中工作?

public static void main(String[] args) { 
    System.out.println("a"); 
    try { 
     System.out.println("b"); 
     throw new IllegalArgumentException(); 
    } catch (IllegalArgumentException e) { 
     System.out.println("c"); 
     throw new RuntimeException(); 
    }catch (RuntimeException e) { 
     System.out.println("d"); 
     throw new RuntimeException(); 
    }finally{ 
     System.out.println("e"); 
     throw new RuntimeException(); 
    } 
} 

該程序的輸出是

a 
b 
c 
e 
Exception in thread "main" java.lang.RuntimeException 

編輯:投擲拋出:IllegalArgumentException後,它前進到對應的catch程序塊和打印 'C'。之後,因爲我們沒有在RuntimeException中捕獲異常,所以它不會再進一步​​。但既然保證了我們去了finally塊,它會打印'e',然後拋出RunttimeException。如果代碼類似於以下內容,則會拋出RuntimeException(「2」)。如果我們最後在內部註釋異常,它會拋出RuntimeException(「1」)。

public static void main(String[] args) throws InterruptedException { 
      System.out.println("a"); 
      try { 
       System.out.println("b"); 
       throw new IllegalArgumentException(); 
      } catch (IllegalArgumentException e) { 

        System.out.println("c"); 
        throw new RuntimeException("1"); 

      }catch (RuntimeException e) { 
       System.out.println("d"); 
       throw new RuntimeException(); 
      }finally{ 
       System.out.println("e"); 
       throw new RuntimeException("2"); 
      } 
     } 

回答

1

在try catch塊,如果catch塊的一個捕獲異常,其他漁獲不介入。記住,無論是否拋出異常,最後阻止總是運行結束。

2

catch該塊未在try的範圍。在catch塊任何代碼執行在外main碼的上下文中,並且因此不具有異常處理程序。當你扔RuntimeExceptionfinally塊的嘗試被執行,然後異常終止程序。

2

這個代碼不打印d是,因爲在拋出:IllegalArgumentException catch塊,後打印「C」,並拋出的RuntimeException它最終執行之前的原因(這是流程是如何工作)。最後,塊本身拋出異常,所以它永遠不會拋出將它變爲「d」的RuntimeException。

public static void main(String[] args) { 
System.out.println("a"); 
try { 
    System.out.println("b"); // 1 
    throw new IllegalArgumentException(); // 2 
} catch (IllegalArgumentException e) { 
    System.out.println("c"); // 3 
    throw new RuntimeException(); // nope, there's a finally block that executes first 
}catch (RuntimeException e) { 
    System.out.println("d"); 
    throw new RuntimeException(); 
}finally{ 
    System.out.println("e"); // 4 
    throw new RuntimeException(); // 5 - rest of the code never got executed. 
} 

}

希望這是很清楚。

而且,有人指出,即使是執行「C」後的RuntimeException,它不會調用下擋塊。 catch塊只調用一次,根據在try塊拋出(雖然因爲第一種解釋決定你的線程的流動,這是不是真的有關)的異常。

相關問題