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");
}

}
}
你们先不编译,看看输出什么?

解决方案 »

  1.   

    finally会在return语句前执行.
    所以会输出"fianlly is Executed".
      

  2.   

    厄.. 没看清楚.. finally里还有个++i;
    还要考虑i=几的问题..
      

  3.   

     ++i 不会执行的吧. 打印语句应该会执行 fianlly is Executed
     the value of i is 1  
      

  4.   

     错了..++i会执行..但不会被return
      

  5.   

    我想知道的就是  ++i 为什么不会执行,后面的打印反而执行
    我有一个理解是return已经把函数的值返回去了,再去执行打印语句,其实i的值已经改变了,只是没有打印出来而已,对不对?请赐教
      

  6.   

    我认为可以这样理解,那个++i是会被执行的 但是不会被返回
    你可以再finally中打印i的值
      

  7.   

    try 中碰到return语句 会跳出try 查看是否有final语句,有则执行,无则返回,
    所以final执行了,所以结果为:fianal is Executed
     the value of i is  1;
      

  8.   

    ++i执行了
    不信在++i后面打印一下i只不过return语句已经确定了值了,应该放到了一个临时变量里,后面的i改变对于这个临时变量没有影响
      

  9.   

    恩  return已经有了确定的值i=1了,然后等待执行,所以后面的++i 虽然执行了但是return值并不改变。
      

  10.   

    怎么理解?那个临时变量是什么来的?是java机制里面的吗?
      

  11.   

    public class Demo_1{
    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");
    } }
    }
      

  12.   

    顶五楼 ++i会执行但不返回 返回的是开始的i值 在main中输出的是开始时返回的值
      

  13.   

    http://zangxt.javaeye.com/blog/421508 
    可以看下这里,讲的比较详细...
    主要就是压栈的问题.
      

  14.   

    try {
        // ... 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
      

  15.   


    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楼的讲的没错
      

  16.   

    http://blog.csdn.net/dengqibin/archive/2010/06/23/5690442.aspx
    这个是我以前写的异常处理流程,可以看看