Home > Java > javaTutorial > Some notes on using Java finally statement

Some notes on using Java finally statement

零下一度
Release: 2017-06-25 10:44:15
Original
1598 people have browsed it

There are many people on the Internet discussing whether the finally statement in the try...catch...finally block in Java's exception catching mechanism will definitely be executed? Many people say no, of course their answer is correct. After my experiments, there are at least two situations where the finally statement will not be executed:

(1) The try statement is not executed, such as It returns before the try statement, so that the finally statement will not be executed. This also shows that the necessary but not sufficient condition for the finally statement to be executed is: the corresponding try statement must be executed.

(2) There is a statement like System.exit(0); in the try block. System.exit(0); terminates the Java virtual machine JVM. Even the JVM stops and everything is over. , of course the finally statement will not be executed.

Of course, many people discuss the relationship between the execution of the Finally statement and return, which is quite confusing. I wonder whether the finally statement is executed before or after the try return? I'm also confused. I don't think what they said is correct. I think it should be: the finally statement is executed after the try return statement is executed and before the return returns. This statement is a bit contradictory. Maybe my expression is not clear enough. Below I will give some results and examples of my own experiments to support it. If you have any questions, you are welcome to ask them.

1. The finally statement is executed after the return statement is executed and before return.

Some notes on using Java finally statement
public class FinallyTest1 {

    public static void main(String[] args) {
        
        System.out.println(test1());
    }

    public static int test1() {
        int b = 20;

        try {
            System.out.println("try block");

            return b += 80; 
        }
        catch (Exception e) {

            System.out.println("catch block");
        }
        finally {
            
            System.out.println("finally block");
            
            if (b > 25) {
                System.out.println("b>25, b = " + b);
            }
        }
        
        return b;
    }
    
}
Copy after login
Some notes on using Java finally statement
##The running result is:

try block
finally block
b>25, b = 100
100
Copy after login
Copy after login
It means that the return statement has been executed before executing the finally statement, but it does not return directly, but waits for the finally statement to be executed before returning the result.

If you feel that this example is not enough to explain this situation, here is another example to strengthen the conclusion:

Some notes on using Java finally statement
public class FinallyTest1 {

    public static void main(String[] args) {
        
        System.out.println(test11());
    }
    
    public static String test11() {
        try {
            System.out.println("try block");

           return test12();
      } finally {
           System.out.println("finally block");
       }
  }

  public static String test12() {
       System.out.println("return statement");

       return "after return";
   }
    
}
Copy after login
Some notes on using Java finally statement
The running result is:

try block
return statement
finally block
after return
Copy after login
It means that the return statement in try is executed first but not immediately Return, wait until finally execution is completed

You may think here: If there is a return statement in finally, does it just return directly, and the return in try cannot return? look down.

2. The return statement in the finally block will override the return return in the try block.

Some notes on using Java finally statement
public class FinallyTest2 {

    public static void main(String[] args) {

        System.out.println(test2());
    }

    public static int test2() {
        int b = 20;

        try {
            System.out.println("try block");

            return b += 80;
        } catch (Exception e) {

            System.out.println("catch block");
        } finally {

            System.out.println("finally block");

            if (b > 25) {
                System.out.println("b>25, b = " + b);
            }

            return 200;
        }

        // return b;
    }

}
Copy after login
Some notes on using Java finally statement
##The running result is:

try block
finally block
b>25, b = 100
200
Copy after login
This means that the return in finally returns directly, regardless of whether there is a return statement in try. There is a small detail to pay attention to. After adding return in finally, the return b outside finally It becomes an unreachable statement, that is, it can never be executed, so it needs to be commented out or the compiler will report an error.

You may think again here: If there is no return statement in finally, but the value of b is modified, then does the return in try return the modified value or the original value? look down.

3. If there is no return statement in the finally statement to overwrite the return value, the original return value may or may not change due to the modification in finally.

Test Case 1:

##
public class FinallyTest3 {

    public static void main(String[] args) {

        System.out.println(test3());
    }

    public static int test3() {
        int b = 20;

        try {
            System.out.println("try block");

            return b += 80;
        } catch (Exception e) {

            System.out.println("catch block");
        } finally {

            System.out.println("finally block");

            if (b > 25) {
                System.out.println("b>25, b = " + b);
            }

            b = 150;
        }

        return 2000;
    }

}
Copy after login
Some notes on using Java finally statement
Some notes on using Java finally statement The running result is:
try block
finally block
b>25, b = 100
100
Copy after login
Copy after login

Test case 2:

import java.util.*;

public class FinallyTest6
{
    public static void main(String[] args) {
        System.out.println(getMap().get("KEY").toString());
    }
     
    public static Map<string> getMap() {
        Map<string> map = new HashMap<string>();
        map.put("KEY", "INIT");
         
        try {
            map.put("KEY", "TRY");
            return map;
        }
        catch (Exception e) {
            map.put("KEY", "CATCH");
        }
        finally {
            map.put("KEY", "FINALLY");
            map = null;
        }
         
        return map;
    }
}</string></string></string>
Copy after login
Some notes on using Java finally statement
Some notes on using Java finally statement

运行结果是:

FINALLY
Copy after login

为什么测试用例1中finally里的b = 150;并没有起到作用而测试用例2中finally的map.put("KEY", "FINALLY");起了作用而map = null;却没起作用呢?这就是Java到底是传值还是传址的问题了,具体请看精选30道Java笔试题解答,里面有详细的解答,简单来说就是:Java中只有传值没有传址,这也是为什么map = null这句不起作用。这同时也说明了返回语句是try中的return语句而不是 finally外面的return b;这句,不相信的话可以试下,将return b;改为return 294,对原来的结果没有一点影响。

这里大家可能又要想:是不是每次返回的一定是try中的return语句呢?那么finally外的return b不是一点作用没吗?请看下面。

4. try块里的return语句在异常的情况下不会被执行,这样具体返回哪个看情况。

Some notes on using Java finally statement
public class FinallyTest4 {

    public static void main(String[] args) {

        System.out.println(test4());
    }

    public static int test4() {
        int b = 20;

        try {
            System.out.println("try block");

            b = b / 0;

            return b += 80;
        } catch (Exception e) {

            b += 15;
            System.out.println("catch block");
        } finally {

            System.out.println("finally block");

            if (b > 25) {
                System.out.println("b>25, b = " + b);
            }

            b += 50;
        }

        return 204;
    }

}
Copy after login
Some notes on using Java finally statement

运行结果是:

try block
catch block
finally block
b>25, b = 35
85
Copy after login
这里因 为在return之前发生了除0异常,所以try中的return不会被执行到,而是接着执行捕获异常的catch 语句和最终的finally语句,此时两者对b的修改都影响了最终的返回值,这时return b;就起到作用了。当然如果你这里将return b改为return 300什么的,最后返回的就是300,这毋庸置疑。

这里大家可能又有疑问:如果catch中有return语句呢?当然只有在异常的情况下才有可能会执行,那么是在finally之前就返回吗?看下面。

5. 当发生异常后,catch中的return执行情况与未发生异常时try中return的执行情况完全一样。

Some notes on using Java finally statement
public class FinallyTest5 {

    public static void main(String[] args) {

        System.out.println(test5());
    }

    public static int test5() {
        int b = 20;

        try {
            System.out.println("try block");
            
            b = b /0;

            return b += 80;
        } catch (Exception e) {

            System.out.println("catch block");
            return b += 15;
        } finally {

            System.out.println("finally block");

            if (b > 25) {
                System.out.println("b>25, b = " + b);
            }

            b += 50;
        }

        //return b;
    }

}
Copy after login
Some notes on using Java finally statement

运行结果如下:

try block
catch block
finally block
b>25, b = 35
35
Copy after login

说明了发生异常后,catch中的return语句先执行,确定了返回值后再去执行finally块,执行完了catch再返回,finally里对b的改变对返回值无影响,原因同前面一样,也就是说情况与try中的return语句执行完全一样。

 

最后总结:finally块的语句在try或catch中的return语句执行之后返回之前执行且finally里的修改语句可能影响也可能不影响try或catch中 return已经确定的返回值,若finally里也有return语句则覆盖try或catch中的return语句直接返回。

学习Java的同学注意了!!!
学习过程中遇到什么问题或者想获取学习资源的话,欢迎加入Java学习交流群:159610322   我们一起学Java!

The above is the detailed content of Some notes on using Java finally statement. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template