这两张图可以清楚的看出来这两者之间的区别了,第一个例子中,在areturn这个指令之前,已经计算出了最后的返回值,setName是在areturn这个指令之后调用;第二个例子,就是正常执行,addSuppressed是在return之前调用。建议题主从jvm指令这个角度分析一下。
贴出我的代码:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.junit.Test;
public class TestExample {
public static class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "Name is " + name + " age is " + age;
}
public void setName(String string) {
this.name = string;
}
}
public String get() {
Student s = new Student("lily", 3); // name, age
try {
int i = 3;
int j = i / 0;
return s.toString();
} catch (Exception e) {
Student t = s;
return t.toString(); // 语句1
} finally {
s.setName("baga");
System.out.println(s.toString()); // 语句2
}
}
@Test
public void test1() {
try {
File file = new File("");
FileInputStream fis = new FileInputStream(file);
Throwable t = null;
try {
fis.read();
} catch (Throwable t1) {
t = t1;
throw t1;
} finally {
if (fis != null) {
if (t != null) {
try {
fis.close();
} catch (Throwable t2) {
t.addSuppressed(t2);
}
} else {
fis.close();
}
}
}
} catch (IOException e3) {
}
}
@Test
public void test() {
String result = get();
System.out.print(result);
}
}