java try catch finally return 继续

之前在博客中有一篇文章讨论过异常中return值的情况,有兴趣可以参见[url]http://gaofulai1988.iteye.com/admin/blogs/2259371[/url],当时的例子比较简单,今天来了特殊点的例子。

在上例子之前,还是回顾以下之前的几个要点:

[b]1. throw 后面的代码是不会执行的。
2. 不管是否有异常,都会执行finally。
3. 不管有多少个return, 只会执行finally里的return。 [/b]


public static int doexception(){
int x=0;
try{
throw new Exception("aaa");
}catch(Exception e){
System.out.println("catch exception");
return ++x;
}finally{
System.out.println("finally ....");
++x;
}
}
public static void main(String args[]){
System.out.println("return value:"+doexception());
}


此时的答案是多少呢?


catch exception
finally ....
return value:1


进入了finally里了,但是不是2,[b]是1[/b]?! 不可思议!看来只能找Oracle来帮我们解答了。

[quote]
If the try clause executes a return, the compiled code does the following:

[b]Saves the return value (if any) in a local variable.[/b]

Executes a jsr to the code for the finally clause.

Upon return from the finally clause, returns the value saved in the local variable.

The compiler sets up a special exception handler, which catches any exception thrown by the try clause. If an exception is thrown in the try clause, this exception handler does the following:

[b]Saves the exception in a local variable.[/b]

Executes a jsr to the finally clause.

Upon return from the finally clause, rethrows the exception.
[/quote] [url]http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.10.2.5[/url]

现在明白了吧,进入到finally里后的操作其实没有什么用,因为之前的变量已经被保存起来了。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值