Java趣味分享:try/finally
考慮以下四個測試方法,它們會輸出什麼?
public class Test {
public static void main(String[] args) {
System.out.println(test1());
System.out.println(test2());
System.out.println(test3());
System.out.println(test4());
}
private static int test1() {
int i = 1;
try {
return i;
} catch (Exception e) {
e.printStackTrace();
} finally {
i = 0;
}
return i;
}
private static int test2() {
int i = 1;
try {
return i;
} catch (Exception e) {
e.printStackTrace();
} finally {
i = 0;
return i;
}
}
private static User test3() {
User user = new User("u1");
try {
return user;
} catch (Exception e) {
e.printStackTrace();
} finally {
user = new User("u2");
}
return null;
}
private static User test4() {
User user = new User("u1");
try {
return user;
} catch (Exception e) {
e.printStackTrace();
} finally {
user.setName("u2");
}
return null;
}
}
public class User {
public User(String name) {
this.name = name;
}
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
答案如下:
1
0
u1
u2
結論
1、不管try,finally都會執行;
2、在try中return,在finally執行前會把結果儲存起來,即使在finally中有修改也以try中儲存的值為準,但如果是引用型別,修改的屬性會以finally修改後的為準;
3、如果try/finally都有return,直接返回finally中的return。
相關文章
- Java try catch finallyJava
- Java try catch finally 總結Java
- 【轉】java中異常與try catch finally詳解Java
- Java中的try、catch、finally塊簡單的解析Java
- JavaScript try catch finally 語句JavaScript
- JavaScript try/catch/finally 語句JavaScript
- Java含有return 的try catch finally的執行順序Java
- JAVA的異常處理機制(一)——try...catch...finallyJava
- 關於Java中try-catch-finally-return的執行順序Java
- [CareerCup] 14.2 Try-catch-finally Java中的異常處理Java
- [Java基礎]try-catch-finally 和 return 的執行順序Java
- Will it finally: 關於 try/catch 的一些細節
- python 中 try...finally... 的優雅實現Python
- c# 異常處理try catch finally_throwC#
- C++及Windows異常處理(try,catch; __try,__finally; __try, __except)——一道筆試題引起的探究C++Windows筆試
- 【搞定面試官】try中有return,finally還會執行嗎?面試
- try-catch-finally,被你忽略掉的執行順序
- C++異常處理:try,catch,throw,finally的用法C++
- c#之異常處理tcbs_try_catch_finallyC#
- java exception and finally returnJavaException
- [Java基礎]FinallyJava
- 有return的情況下try catch finally的執行順序
- (轉)有return的情況下try catch finally的執行順
- Effective C#:利用using和try/finally語句來清理資源C#
- Java的finally語句Java
- Java 7 Try-With-ResourcesJava
- try/catch/finally:“前端的好厚米,我覺得你們不夠了解我呀~”前端
- java中try catch塊的使用Java
- java中的finally詳解(finally中沒有return i,卻有i=XX)Java
- Java之異常處理try{}catch(){}Java
- java中的try-with-resource語法Java
- Java中try()catch{}的使用方法Java
- 技術趣味史-Java語言的身世Java
- Java 常見異常及趣味解釋Java
- 【java】final、finally、finallize的區別Java
- java finally一定會執行嗎Java
- 有return的情況下try catch finally的執行順序(最有說服力的總結)
- Java基礎-try-with-resource語法糖Java