先上代码: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的正常运行,真的????
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的正常运行,真的????
而System.out.println()则输出到System.out这个流里了。吧printStackTrace都换成System.out.println(e)应该就是正常结果了。
但是,不同只是发生在把代码稍微作下改动之后,比如在某处多加一条打印语句等
然而奇怪的是,多运行几次之后,结果就一样了关注ing
几次刚好相等不能说明问题。
........
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重定向到文件。
而这段代码的执行结果却为什么没有像前面的那样出现并发?
每次文件中产生的内容都是一致的。