我编写了下面的代码,取自 Java How to program 9th Edition - Paul 和 Michelle Harvey - 代码工作正常,但问题是每次执行它时,它都会给我不确定的异常处理结果 - 例如请查看代码片段的输出。你能帮我理解为什么会发生这种行为吗?
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
输出: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.