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 finally 總結Java
- 謹慎 try-finally
- 【轉】java中異常與try catch finally詳解Java
- JavaScript try catch finally 語句JavaScript
- JavaScript try/catch/finally 語句JavaScript
- try-catch-finally的使用
- JAVA的異常處理機制(一)——try...catch...finallyJava
- [Java基礎]try-catch-finally 和 return 的執行順序Java
- python 中 try...finally... 的優雅實現Python
- Will it finally: 關於 try/catch 的一些細節
- try-catch-finally,被你忽略掉的執行順序
- 【搞定面試官】try中有return,finally還會執行嗎?面試
- java exception and finally returnJavaException
- [Java基礎]FinallyJava
- 有return的情況下try catch finally的執行順序
- (轉)有return的情況下try catch finally的執行順
- Java 7 Try-With-ResourcesJava
- 【java】final、finally、finallize的區別Java
- try/catch/finally:“前端的好厚米,我覺得你們不夠了解我呀~”前端
- Java中final、finally、finalize的區別Java
- Java中final,finally,finalize的區別Java
- java finally一定會執行嗎Java
- Java之異常處理try{}catch(){}Java
- java中的try-with-resource語法Java
- Java中try()catch{}的使用方法Java
- 【Java面試題系列】:Java中final finally finalize的區別Java面試題
- 技術趣味史-Java語言的身世Java
- try{}裡有一個return語句,那麼緊跟在這個try後的finally{}裡的code會不會被執行,什麼時候被執行?
- java try(){}catch(){}自動資源釋放Java
- Java基礎-try-with-resource語法糖Java
- 技術趣味史-Java 各個版本的特性Java
- TRy
- final:finalize:finally:
- Java之try-catch和throws的區別Java
- Effective Java -- 使用try-with-resources優化程式碼Java優化
- Jumping with Try
- try ,catch
- 『Java 語法基礎』final、finalize 和 finally 的不同之處Java