在上例子之前,还是回顾以下之前的几个要点:
1. throw 后面的代码是不会执行的。
2. 不管是否有异常,都会执行finally。
3. 不管有多少个return, 只会执行finally里的return。
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, 是1?! 不可思议!看来只能找Oracle来帮我们解答了。
引用
If the try clause executes a return, the compiled code does the following:
Saves the return value (if any) in a local variable.
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:
Saves the exception in a local variable.
Executes a jsr to the finally clause.
Upon return from the finally clause, rethrows the exception.
现在明白了吧,进入到finally里后的操作其实没有什么用,因为之前的变量已经被保存起来了。