java中异常处理顺序问题!!!不同次执行结果不同
网上看到的一个程序,执行多次结果均不相同。
public class cc{
public static void main(String args[]){
try{
throwException();
}
catch (Exception e){
System.err.println("Exception handled in main");
}
doesNotThrowException();
}
public static void throwException() throws Exception{
try{
System.out.println("Method throwException");
throw new Exception();
}
catch(Exception e){
System.err.println("Exception handled in method throwException");
throw e;
}
finally{
System.err.println("Finally is always executed");
}
}
public static void doesNotThrowException(){
try{
System.out.println("Method doesNotThrowException");
}
catch (Exception e){
System.err.println(e.toString());
}
finally{
System.err.println("Finally is always executed.");
}
}
}
结果一:
Method throwException
Exception handled in method throwException
Finally is always executed
Exception handled in main
Method doesNotThrowException
Finally is always executed!!!
结果二:
Method throwException
Method doesNotThrowException
Exception handled in method throwException
Finally is always executed
Exception handled in main
Finally is always executed!!!
结果三:
Method throwException
Exception handled in method throwException
Finally is always executed
Exception handled in main
Finally is always executed!!!
Method doesNotThrowException
结果N:
……
多个版本,为什么执行顺序会不同呢,我是在eclipse中编译执行的。
求高手解惑!!! Java 异常处理 Eclipse finally 顺序不同
[解决办法]
System.err.println只能在屏幕上实现打印,即使你重定向了也一样。重定向这个词,,就是其本意,就是本来往一个地方输出,你可以修改他的方向,让他把内容输出到其他地方。System.out 就是一个输出流,默认是往控制台输出。你可以重新设值他的输出方向,比如输出到文件里面。这个行为就叫重定向。
要想输出顺序不变,就把err改成out