thinking in java异常这章一问
//: c09:FinallyWorks.java
// The finally clause is always executed.
import com.bruceeckel.simpletest.*;
class ThreeException extends Exception {}
public class FinallyWorks {
private static Test monitor = new Test();
static int count = 0;
public static void main(String[] args) {
while(true) {
try {
// Post-increment is zero first time:
if(count++ == 0)
throw new ThreeException();
System.out.println( "No exception ");
} catch(ThreeException e) {
System.err.println( "ThreeException ");
} finally {
System.err.println( "In finally clause ");
if(count == 2) break; // out of "while "
}
}
monitor.expect(new String[] {
"ThreeException ",
"In finally clause ",
"No exception ",
"In finally clause "
});
}
} ///:~
我运行的结果是
ThreeException
In finally clause
In finally clause
No exception
请大家帮忙分析一下 ,那种正确??最好对程序进行讲解一下,我看这章有点晕......
------解决方案--------------------System.err.println( "ThreeException ");
System.err.println( "In finally clause ");
System.out.println( "No exception ");
System.err.println( "In finally clause ");
抛出异常 中断执行
catch 捕获异常 打印 ThreeException
finally中 打印 In finally clause
继续循环
未出现异常 不中断 打印 No exception
没有异常给catch捕获
然后finally 打印 In finally clause
循环结束
------解决方案--------------------MARK
占了位置等高手~~~
------解决方案--------------------mark
------解决方案--------------------这跟系统处理err和out的顺序有关,如果把所有的err都改成out,就是正常的顺序了:
ThreeException
In finally clause
No exception
In finally clause
一般来说,err是立即输出到显示的,而out是有buffer的,所以显示顺序看上去有问题。
"By convention, this output stream is used to display error messages or other information that should come to the immediate attention of a user even if the principal output stream, the value of the variable out, has been redirected to a file or other destination that is typically not continuously monitored. "