try catch finally 执行顺序?

migo2008 2009-07-30 04:43:08
先上代码:

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的正常运行,真的????
...全文
290 8 打赏 收藏 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
migo2008 2009-07-30
  • 打赏
  • 举报
回复

........
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重定向到文件。
而这段代码的执行结果却为什么没有像前面的那样出现并发?
每次文件中产生的内容都是一致的。
migo2008 2009-07-30
  • 打赏
  • 举报
回复
谢谢各位,的确如各位所讲,是system.err与system.out之间并发出现的问题。
wzj167 2009-07-30
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 lovecj6185 的回复:]
恩,运行结果确实是不同
但是,不同只是发生在把代码稍微作下改动之后,比如在某处多加一条打印语句等
然而奇怪的是,多运行几次之后,结果就一样了

关注ing
[/Quote]
只要System.err和System.out这两个并发,应该输出顺序就是随即的。
几次刚好相等不能说明问题。
lovecj6185 2009-07-30
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 dollyn 的回复:]
是e.printStackTrace();这方法的问题,这个方法,是向System.error这个流里输出。
而System.out.println()则输出到System.out这个流里了。

吧printStackTrace都换成System.out.println(e)应该就是正常结果了。
[/Quote]

试验了一下,确实是这样,学习了
lovecj6185 2009-07-30
  • 打赏
  • 举报
回复
恩,运行结果确实是不同
但是,不同只是发生在把代码稍微作下改动之后,比如在某处多加一条打印语句等
然而奇怪的是,多运行几次之后,结果就一样了

关注ing
霜之哀伤 2009-07-30
  • 打赏
  • 举报
回复
是e.printStackTrace();这方法的问题,这个方法,是向System.error这个流里输出。
而System.out.println()则输出到System.out这个流里了。

吧printStackTrace都换成System.out.println(e)应该就是正常结果了。
ThirstyCrow 2009-07-30
  • 打赏
  • 举报
回复
printStackTrace()是将错误信息输出到System.err, 而"finally"是输出到System.out, 所以输出顺序是不确定的。
wzj167 2009-07-30
  • 打赏
  • 举报
回复
关注

62,620

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧