in the following example
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
}
statement 2 executes before statement 1. The result is that Name is baga age is: 3
statement 1 returns the following:
Name is lily age is: 3
, which means that return is a deep copy of s, and s cannot be affected by finally blocks
Grammar Sugar 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){
...
}
where we see
in the catch blockt=t1;
throw t1;
then the following:
t.addSuppressed(t2);
T2 can be carried by the T1 that can be thrown, indicating that throw T1 retains a shallow copy and can be affected by finally blocks
.what is the difference?