先上代码:package com.think.chapter12;
class A extends Exception{
@Override
public String toString() {
return "this is A";
}
}class B extends Exception{
@Override
public String toString() {
return "this is B";
}
}public class LostMessage { void f() throws A{
throw new A();
}

void g() throws B{
throw new B();
}

public static void main(String[] args) {
LostMessage lm = new LostMessage();
try{
try{
lm.f();
}finally{
lm.g();
}
}catch(Exception b){
b.printStackTrace();
}finally{
System.out.println("finally");
//return;  
}
}
}再上结果:
this is Bfinally at com.think.chapter12.LostMessage.g(LostMessage.java:23)
at com.think.chapter12.LostMessage.main(LostMessage.java:32)

finally
this is B
at com.think.chapter12.LostMessage.g(LostMessage.java:25)
at com.think.chapter12.LostMessage.main(LostMessage.java:34)


this is B
at com.think.chapter12.LostMessage.g(LostMessage.java:25)
at com.think.chapter12.LostMessage.main(LostMessage.java:34)
finally

请问:
为什么会出现几种不同的结果?p.s. 以上结果是finally子块中的return被注释之后产生的结果。
     网上看到说finally中的return会影响到JVM的正常运行,真的????

解决方案 »

  1.   

    printStackTrace()是将错误信息输出到System.err, 而"finally"是输出到System.out, 所以输出顺序是不确定的。
      

  2.   

    是e.printStackTrace();这方法的问题,这个方法,是向System.error这个流里输出。
    而System.out.println()则输出到System.out这个流里了。吧printStackTrace都换成System.out.println(e)应该就是正常结果了。
      

  3.   

    恩,运行结果确实是不同
    但是,不同只是发生在把代码稍微作下改动之后,比如在某处多加一条打印语句等
    然而奇怪的是,多运行几次之后,结果就一样了关注ing
      

  4.   

    只要System.err和System.out这两个并发,应该输出顺序就是随即的。
    几次刚好相等不能说明问题。
      

  5.   

    谢谢各位,的确如各位所讲,是system.err与system.out之间并发出现的问题。
      

  6.   


      ........
                            System.setOut(print);
    System.setErr(print);
    String s = null;
    try{
    System.out.println("test");
    s.charAt(1);
    }catch(Exception ex){
    ex.printStackTrace();
    }finally{
    System.err.println(e);
    }
    print.close();
    ......上面的代码中,将System.err和System.out重定向到文件。
    而这段代码的执行结果却为什么没有像前面的那样出现并发?
    每次文件中产生的内容都是一致的。