finally在try和catch塊以及return中的執行順序
阿新 • • 發佈:2019-01-08
執行順序
無catch時
- finally會在try包含的return之後執行,會在try外面的return之前執行
當有catch時
- finally是在catch執行之後catch包含的return之前執行的
執行順序圖
try包含的return
|
v
catch
|
v
finally
|
v
catch包含的return
|
v
try外面的return(和catch塊不能並存)
DEMO驗證
package abc;
/**
* @ClassName: Test1
* @Description: TODO(這裡用一句話描述這個類的作用)
* @author bamboo <a href="mailto:[email protected]?subject=hello,bamboo&body=Dear Bamboo:%0d%0a描述你的問題:">Bamboo</a>
* @date 2017年3月2日 下午2:49:55
* @since
*/
public class Test1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
testa();
}
public static Object testa() {
// TODO Auto-generated method stub
StringBuffer sb = new StringBuffer("");
try {
return print(sb);
} finally {
sb.append("finally");
System.out.println(sb.toString());
}
}
public static Object testb() {
// TODO Auto-generated method stub
StringBuffer sb = new StringBuffer("");
try {
} finally {
sb.append("finally");
System.out.println(sb.toString());
}
return print(sb);
}
public static Object testc() {
// TODO Auto-generated method stub
StringBuffer sb = new StringBuffer("");
try {
int a=1;
if(1==a){
throw new Exception();
}
return print(sb);
}catch(Exception e){
sb.append("catch");
return print(sb);
}finally {
sb.append("finally");
System.out.println(sb.toString());
}
}
public static Object print(StringBuffer sb) {
// TODO Auto-generated method stub
sb.append("return");
System.out.println(sb.toString());
return null;
}
}
testa()方法ouput:
return
returnfinally
testa()方法是return在try的裡面,從結果看先執行的retrun然後執行的finally;
testb()方法ouput:
finally
finallyreturn
testb()方法是return在try的外面,從結果看先執行的finally然後執行的retrun;
testc()方法ouput:
catchreturn
catchreturnfinally
testb()方法是return在try的外面,從結果看先執行的finally然後執行的retrun;