三点总结:
1.finally块的语句在try或catch中的return语句执行之后返回之前执行。
2.finally里的修改语句可能影响也可能不影响try或catch中 return已经确定的返回值
3.若finally里也有return语句则覆盖try或catch中的return语句直接返回。
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class Test2 {
public static void main(String[] args) {
Test2 m = new Test2();
System.out.println(m.amethod1());//1进入amethod1
}
public int amethod1() {
try {
new FileInputStream("Hello.txt");
} catch (FileNotFoundException e) {
System.out.println("catch block");//2输出catch block
return amethod2();//3进入amethod2
}finally{
System.out.println("finally block");//6输出
}
return 0;//上面已经return 不执行
}
public static int amethod2() {
System.out.println("return mathod");//4输出
return -1;//5执行 7返回输出
}
}
输出结果:
catch block
return mathod
finally block
-1
例2
public class Test1 {
public static void main(String[] args) {
System.out.println(test1());
}
public static int test1() {
int b = 20;
try {
System.out.println("try block");//1输出
return b += 80; //2执行 5返回输出
}
catch (Exception e) {
System.out.println("catch block");
}
finally {
System.out.println("finally block");//3输出
if (b > 25) {
System.out.println("b>25, b = " + b);//4输出
}
// return b;
}
return b;//不执行
}
}
输出结果:
try block
finally block
b>25, b = 100
100
例3:与例2对比
public class Test1 {
public static void main(String[] args) {
System.out.println(test1());
}
public static int test1() {
int b = 20;
try {
System.out.println("try block");//1输出
return b += 80; //2执行
}
catch (Exception e) {
System.out.println("catch block");
}
finally {
System.out.println("finally block");//3输出
if (b > 25) {
System.out.println("b>25, b = " + b);//4输出
}
return b+1;//5 执行输出
}
//return b;
}
}
输出结果:
try block
finally block
b>25, b = 100
101