try的return和finally相关问题
(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");
}
}
}
【代码摘自:】
(4)如果try和finally都有return,finally的return会覆盖try的return。执行f(2),返回0.(这一点采用第3条相同的理解)
【图片摘自javaguide】
