finally和return的执行顺序
今天看到一段代码,try中有return语句,后面还有一个finally,不知道执行过程是什么样的。于是来试验了一下。
1.try和catch中有return时,finally里面的语句会被执行吗
我们可以来分别看看
(1)执行try中的return时
public class tryDemo {
public static int show() {
try {
return 1;
}finally{
System.out.println("finally模块被执行");
}
}
public static void main(String args[]) {
System.out.println(show());
}
}
输出结果如下:
(2)执行catch中的return时
public class tryDemo {
public static int show() {
try {
int a = 8/0;
return 1;
}catch (Exception e) {
return 2;
}finally{
System.out.println("finally模块被执行");
}
}
public static void main(String args[]) {
System.out.println(show());
}
}
其结果如下:
我们可以得出结论:
如果程序是从try代码块或者catch代码块中返回时,finally中的代码总会执行。而且finally语句在return语句执行之后return返回之前执行的。可以使用编译器的Debug功能查看详细过程。
2.如果finally也有return的时候……
public class tryDemo {
public static int show() {
try {
int a = 8/0;
return 1;
}catch (Exception e) {
return 2;
}finally{
System.out.println("finally模块被执行");
return 0;
}
}
public static void main(String args[]) {
System.out.println(show());
}
}
执行结果如下:
结论:
我们可以看到当finally有返回值时,会直接返回。不会再去返回try或者catch中的返回值。
3.finally中对于返回变量做的改变会影响最终的返回结果吗
我们先来看一看如果try或者catch中的返回值是普通变量时。
public class tryDemo {
public static int show() {
int result = 0;
try {
return result;
}finally{
System.out.println("finally模块被执行");
result = 1;
}
}
public static void main(String args[]) {
System.out.println(show());
}
}
执行的结果如下:
并不会改变返回的内容。
当返回的变量的类型是引用类型时,结果也是一样的
代码如下:
public class tryDemo {
public static Object show() {
Object obj = new Object();
try {
return obj;
}finally{
System.out.println("finally模块被执行");
obj = null;
}
}
public static void main(String args[]) {
System.out.println(show());
}
}
结果如下:
我们可以得出以下结论:
如果try和catch的return是一个变量时且函数的是从其中一个返回时,后面finally中语句即使有对返回的变量进行赋值的操作时,也不会影响返回的值。