下面的例子中
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
}
语句2先于语句1执行,结果是 Name is baga age is: 3
语句1返回的是:
Name is lily age is: 3
这说明return的是s的一个深拷贝,s不能被finally块影响了
语法糖try with resource
try(FileInputStream fis = new FileInputStream(file)){
fis.read();
} catch (IOException e3){
...
}
反编译其实就是
try{
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){
...
}
其中我们看到catch块中
t=t1;
throw t1;
然后下面:
t.addSuppressed(t2);
t2能被抛出的t1携带,说明 throw t1保留的是一个浅拷贝,能被finally块影响
这个区别是为何?
不是这样的。其实是catch块里面的
s.toString()
先执行,再执行finally块里的内容,然后再执行return。所以,最后返回的内容其实是为执行finally块之前的s的内容。