0
我已經寫了下面的代碼如何編程第9版 - 保羅和米歇爾哈維 - 代碼工作正常,但問題是,每次我執行它,它給了我不確定的結果哪些例外處理 - 例如請查看代碼片段的輸出。你能幫我理解爲什麼會發生這種行爲嗎?異常處理輸出消息
public class Test {
public static void main(String[] args) {
try {
// call method throwException
throwException();
}// end try
catch (Exception e) {
System.out.println("Exception handled in main");
}// end catch
// call method doesNotThrowException
doesNotThrowException();
}
private static void throwException() throws Exception {
try {
System.out.println("Method throwException.");
throw new Exception(); // generate exception
}
catch (Exception exception) {
System.err.println("Exception handled in method throwException");
throw exception;
}
// executes regardless of what occurs in try ... catch block
finally {
System.err.println("Finally executed in throwException.");
}
}// end of method throwException
private static void doesNotThrowException() {
try {
System.out.println("Method doesNotThrowException.");
}
// catch does not execute as the method does not throw any exceptions
catch (Exception exception) {
System.err.println(exception);
}// end catch
// executes regardless of what occurs in try ... catch block
finally {
System.err.println("Finally executed in doesNotThrowException");
}
}// end of deosNotThrowException
}//end Test Class
OUTPUTS: 1)
Method throwException.
Exception handled in method throwException
Finally executed in throwException.
Finally executed in doesNotThrowException
Exception handled in main
Method doesNotThrowException.
2)在不同的運行
Exception handled in method throwException
Finally executed in throwException.Method throwException.
Finally executed in doesNotThrowException
Exception handled in main
Method doesNotThrowException.
你的問題不清楚。輸出1和2?爲什麼這樣?你在2次不同的運行中得到不同的結果? – m0skit0 2012-04-09 11:11:04
是的你是對的 - 我在兩次不同的跑步中得到了不同的結果!那實際上是我的問題 - 我不知道爲什麼會發生這種行爲。 – Sinan 2012-04-09 11:13:26