(1)try塊的return和finally的執行順序。try執行之後,return之前會跳轉到finally執行代碼。
(2)是否有可能執行了try不執行finally?如果在try調用了system.exit(0),就不會執行到finally。
(3)finally何時會影響返回值?(可以這麼理解:try已經執行了return,然後調用finally代碼塊,若修改的是本地變量,finally不會對返回值造成影響,如果修改的是堆中的對象,則會造成影響)
如果返回值是基礎類型,finally中的修改不會影響try的return。以下代碼輸出爲10.
public class TestTryCatch {
public static void main(String[] args)
{
TestTryCatch test = new TestTryCatch();
System.out.println(test.fun());
}
public int fun()
{
int i = 10;
try
{
return i;
}catch(Exception e){
return i;
}finally{
i = 20;
}
}
}
如果是引用類型,finally的代碼會影響到try,因爲對象地址相同。以下代碼輸出爲helloworldfinally.
public class TestTryCatch {
public static void main(String[] args)
{
TestTryCatch test = new TestTryCatch();
System.out.println(test.fun());
}
public StringBuilder fun()
{
StringBuilder s = new StringBuilder("hello");
try
{
s.append("world");
return s;
}catch(Exception e){
return s;
}finally{
string.append("finally");
}
}
}
【代碼摘自:https://blog.csdn.net/weixin_41005006/article/details/80643681】
(4)如果try和finally都有return,finally的return會覆蓋try的return。執行f(2),返回0.(這一點採用第3條相同的理解)
【圖片摘自javaguide】