之前在博客中有一篇文章讨论过异常中return值的情况,有兴趣可以参见[url]http://gaofulai1988.iteye.com/admin/blogs/2259371[/url],当时的例子比较简单,今天来了特殊点的例子。
在上例子之前,还是回顾以下之前的几个要点:
[b]1. throw 后面的代码是不会执行的。
2. 不管是否有异常,都会执行finally。
3. 不管有多少个return, 只会执行finally里的return。 [/b]
此时的答案是多少呢?
进入了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里后的操作其实没有什么用,因为之前的变量已经被保存起来了。
在上例子之前,还是回顾以下之前的几个要点:
[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里后的操作其实没有什么用,因为之前的变量已经被保存起来了。