关于return和finally

本来return和finally也不是个事。之前看虚拟机运行原理的时候就了解过。但是最近被人问起的时候,缺没有说清楚。所以整理一下记录下来。
[b]1.如果返回的是个对象,finally里的的代码,可以改变对象内部的状态。[/b]
package com.chinaso.phl;

import java.util.ArrayList;
import java.util.List;

public class Test {

public static void main(String[] args) throws Exception {
Test t = new Test();
System.out.println(t.check());
}

public List<String> check() throws Exception {
List<String> name = new ArrayList<String>();
name.add("phl");
try {
System.out.println("try");
return name;
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("finally");
name.add("piaohailin");
for (int i = 0; i < 3; i++) {
System.out.println("time:" + (i + 1) * 300);
Thread.sleep(300);
}
}
System.out.println("return");
name.add("return");
return name;
}
}

输出
try
finally
time:300
time:600
time:900
[phl, piaohailin]

[b]2.finally里面的赋值,不会影响返回结果[/b]
package com.chinaso.phl;

import java.util.ArrayList;
import java.util.List;

public class Test {

public static void main(String[] args) throws Exception {
Test t = new Test();
System.out.println(t.check());
}

public String check() throws Exception {
String name = "phl";
try {
System.out.println("try");
return name;
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("finally");
name = "piaohailin";
for (int i = 0; i < 3; i++) {
System.out.println("time:" + (i + 1) * 300);
Thread.sleep(300);
}
}
System.out.println("return");
name = "return";
return name;
}
}

输出
try
finally
time:300
time:600
time:900
phl

[b]3.finally里带有return方法,则此return会覆盖try里面的return[/b]
//warnning finally block does not complete normally
一般不这么用,因为有警告信息,不够优雅
package com.chinaso.phl;

import java.util.ArrayList;
import java.util.List;

public class Test {

public static void main(String[] args) throws Exception {
Test t = new Test();
System.out.println(t.check2());
}

public String check2() throws Exception {
String name = "phl";
try {
System.out.println("try");
return name;
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("finally");
name = "piaohailin";
for (int i = 0; i < 3; i++) {
System.out.println("time:" + (i + 1) * 300);
Thread.sleep(300);
}
return name;
}
}
}

输出
try
finally
time:300
time:600
time:900
piaohailin
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值