阅读2分钟,掌握一个Java小细节,你值得拥有!
java面试经常能看到这道题目:
try {} 里有一个return语句,那么紧跟在这个try后的finally {}里的代码会不会被执行?什么时候被执行?在return前还是后?
try/catch/finally 都有return 语句
public class tryCatchDemo {
public static void main(String[] args) {
String str = testTryCatch();
System.out.println(str);
}
public static String testTryCatch(){
int index = ;
try{
index++;
return "tryReturn"+index;
}
catch (Exception e){
index = index-;
return "catchReturn"+index;
}
finally {
index--;
return "finallyReturn"+index;
}
}
}
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLiAzNvwVZ2x2bzNXak9CX90TQNNkRrFlQKBTSvwFbslmZvwFMwQzLcVmepNHdu9mZvwFVywUNMZTY18CX052bm9CX9UEVNhXVYVWdWdUY2YFSiZXUYpVd1kmYr50MZV3YyI2cKJDT29GRjBjUIF2LcRHelR3LcJzLctmch1mclRXY39zNzUzM0YTM1EzNxIDM4EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
再看一个例子,注意看执行顺序,非常重要
public class tryCatchDemo {
public static void main(String[] args) {
String str = testTryCatch();
System.out.println(str);
}
public static String testTryCatch() {
int index = ;
try {
index++;
return "tryReturn" + (++index);
} catch (Exception e) {
index = index + ;
return "catchReturn" + (++index);
} finally {
//index--;
return "finallyReturn" + index;
}
}
}
在try和finally中都有return的情况下,会先执行try中return语句,然后执行finally。所以千万得注意到这个执行顺序,会影响到最终得返回值。
try/catch 有return语句
public static void main(String[] args) {
String str = testTryCatch();
System.out.println(str);
}
public static String testTryCatch() {
int index = ;
try {
index++;
String nullStr = null;
nullStr.toString();
return "tryReturn" + (++index);
} catch (Exception e) {
index = index + ;
return "catchReturn" + (++index);
} finally {
System.out.println("finally");
}
}
无论是try还是catch,都会先执行return语句然后再执行finally。
总结:
1、不管有没有出现异常,finally块中代码都会执行;
2、当try和catch中有return时,finally仍然会执行;
3、finally是在return后面的表达式运算后执行的(此时并没有返回运算后的值,而是先把要返回的值保存起来,不管finally中的代码怎么样,返回的值都不会改变,任然是之前保存的值),所以函数返回值是在finally执行前确定的;
4、finally中最好不要包含return,否则程序会提前退出,返回值不是try或catch中保存的返回值。
finally中最好不要有return,阿里编程规约也约定了。