2013-10-19 30 views
-1

這是測驗中的一個問題,我很困惑。 鑑於代碼片斷:例外順序

public void foo(){ 
    try{ 
     System.out.println(「starting」); 
     bar(); 
     System.out.println(「passed bar」); 
    }catch(Exception e){ 
     System.out.println(「foo exception」); 
} 

給上述IF條()拋出異常的方法foo()的輸出

我的回答是:

開始

FOO例外

這是正確的嗎?

你能告訴我怎樣才能測試它或向我解釋? 非常感謝您的幫助!

我現在明白了, 謝謝你這麼多,非常快的和有益的反應

+0

它取決於在拋出異常之前是否輸出任何東西。 –

+0

除了Pete Kirkham之外,還依賴於在酒吧方法中你捕捉到任何異常。 – berkay

+0

您忘記了第一個端架嗎?你正在關閉嘗試但不關閉該方法。 –

回答

1

您可以測試它是這樣:

public static void main(String[] args) { 
    try { 
     System.out.println("Starting"); 
     bar(); 
     System.out.println("passed bar"); 
    } catch (Exception e) { 
     System.out.println("foo exception"); 
    } 
} 

private static void bar() throws Exception { 
    throw new Exception(); 
} 

產量預期:

開始
foo的例外

第一行顯示爲預期。之後,它將轉到bar(),該錯誤會引發錯誤並立即在catch塊中繼續。該塊輸出第二條消息。

+0

如果我在bar方法中遇到異常,該怎麼辦? – berkay

+0

然後在主要的try-catch中不會出現異常。將顯示「通過酒吧」而不是「foo例外」。當然你可以用我給你的密碼自己試試 –

0

您可以通過編寫bar()方法自己測試這個:P

void bar() throws Exception { 
    throw new Exception(); 
} 
1

你是正確的,第一println將簡單地沒有問題跑,然後bar運行,並拋出一個異常,因爲你有一個try內包含它,並已覆蓋了所有類型的異常最抽象的異常(Exception型)因此所有類型的異常都會被捕獲,當發生這種情況時,catch代碼塊將運行(意味着將打印「foo異常」),並且程序將照常繼續進行任何操作。因爲它被抓到第二個println將永遠不會運行。

+0

謝謝李。現在我很清楚 – ThankYouForHelping

0

除了吉榮Vannevel的回答下面的代碼輸出爲:

Starting 
i catched an exception in bar() 
passed bar 

public static void main(String[] args) { 
     try { 
      System.out.println("Starting"); 
      bar(); 
      System.out.println("passed bar"); 
     } catch (Exception e) { 
      System.out.println("foo exception"); 
     } 
    } 

    private static void bar() throws Exception { 
     try { 
      throw new Exception(); 
     } catch (Exception e) { 
      System.out.println("i catched an exception in bar()"); 
     } 
    }