public class Demo_1{
public static void main (String[] args){
System.out.println (" the value of i is" + new Demo_1().test());
}
private int test(){
int i = 1;
try{
return i;
}finally{
++i ;
System.out.println ("fianlly is Executed");
}
}
}
你们先不编译,看看输出什么?
public static void main (String[] args){
System.out.println (" the value of i is" + new Demo_1().test());
}
private int test(){
int i = 1;
try{
return i;
}finally{
++i ;
System.out.println ("fianlly is Executed");
}
}
}
你们先不编译,看看输出什么?
所以会输出"fianlly is Executed".
还要考虑i=几的问题..
the value of i is 1
我有一个理解是return已经把函数的值返回去了,再去执行打印语句,其实i的值已经改变了,只是没有打印出来而已,对不对?请赐教
你可以再finally中打印i的值
所以final执行了,所以结果为:fianal is Executed
the value of i is 1;
不信在++i后面打印一下i只不过return语句已经确定了值了,应该放到了一个临时变量里,后面的i改变对于这个临时变量没有影响
public static void main (String[] args){
System.out.println (" the return value is" + new Demo_1().test());
}
private int test(){
int i = 1;
try{
return i;
}finally{
++i ;
System.out.println (" the value of i is " + i);
System.out.println ("fianlly is Executed");
} }
}
可以看下这里,讲的比较详细...
主要就是压栈的问题.
// ... do something ...
return 1;
} finally {
return 2;
}When the TRy block executes its return, the finally block is entered with the "reason" of returning the value 1. However, inside the finally block the value 2 is returned, so the initial intention is forgotten. In fact, if any of the other code in the try block had thrown an exception, the result would still be to return 2. If the finally block did not return a value but simply fell out the bottom, the "return the value 1" reason would be remembered and carried out.
——摘自《THE Java™ Programming Language, Fourth Edition》By Ken Arnold, James Gosling, David Holmes
public class Demo_1{
public static void main (String[] args){
System.out.println (" the value of i is--> " + new Demo_1().test());
}
public int test(){
int i = 1;
try{
return i;
}finally{
++i ;
System.out.println ("fianlly is Executed");
return ++i;
}
}
}输出
fianlly is Executed
the value of i is--> 318楼的讲的没错
这个是我以前写的异常处理流程,可以看看