The return keyword in the exception handling mechanism.

Source: Internet
Author: User

The return keyword in the exception handling mechanism.

 

In Java, note the following before executing the try-catch-finally statement:

First, the return statement is not the final exit of the function. If there is a finally statement, it will execute finally after return (the return value will be saved in the stack, wait for finally execution before returning)

Second, the return statement is not recommended in finally. As needed, the return statement can be placed in try and catch and at the end of the function. There are four feasible methods:

1) The return statement appears only once at the last time of the method.

2) The return statement only appears in try and catch.

3) The return statement only appears at the end of try and method.

4) The return statement only appears at the end of the catch and method statements.

Note that other methods are not feasible and the compiler reports an error.

(1) If you can return results when the program runs try successfully, use method 2.

(2) If you do not need to continue executing the code after a catch (that is, when an error occurs in the middle), Method 4 is adopted.

(3) If you still need to continue executing the code after running try or catch, method 1 is adopted.

 

Demo 1:

Package cn. day006; public class Test {public static void main (String [] args) {System. out. println (getResult () ;}@ SuppressWarnings ("finally") public static int getResult () {int a = 100; try {return a + 1; // note, the basic data type of java is value passing. The returned value has nothing to do with a.} catch (Exception e) {e. printStackTrace () ;}finally {return a; // finally redirect the value to a (equivalent to overwriting the return value in try), so the output is still 100 }}}

Execution result: 100

 

Demo 2:

Package cn. day006; public class Test {public static void main (String [] args) {System. out. println (getResult () ;}@ SuppressWarnings ("finally") public static int getResult () {int a = 100; try {return a ++; // remember a ++ ----> a = a + 1. At this time, the value of a is changed.} catch (Exception e) {e. printStackTrace () ;}finally {return ;}}}

Execution result: 101

 

Demo 3:

package cn.day006;public class Test {     public static void main(String[] args) {            System.out.println(getResult());        }        public static int getResult(){            int a =100;                        try{                  a++;                return a;                          }finally{                a++;               }        }}

The result is 101.

 

Analysis:

In the try statement, when the return statement is executed, the results to be returned are ready. At this time, the program is switched to finally for execution.

Before forwarding, try to store the results to be returned in local variables different from x. After finally execution, retrieve the returned results,

Therefore, even if the variable x is changed in finally, the returned results are not affected.

It should use the stack to save the return value.

 

Demo 4:

Package cn. day006; public class Test2 {public static void main (String [] args) {try {System. out. println (getResult ();} catch (Exception e) {e. printStackTrace (); System. out. println ("catch exceptions");} finally {System. out. println ("Exception Handling finally") ;}@ SuppressWarnings ("finally") public static int getResult () throws Exception {int a = 100; try {a = a + 10; throw new RuntimeException ();} catch (Exception e) {System. out. println ("intercepting exceptions and throwing exceptions again"); throw new Exception () ;}finally {return ;}}}

The result is as follows:

Intercept exceptions and throw exceptions again
110
Exception Handling finally

 

The key "catch exception" was not executed !!!

The reason is that return a value in finally of getResult (), which is equivalent to telling the compiler that the method has no exception, but actually there are some exceptions, the result is that the caller of this method cannot catch the exception, and the exception is swallowed up without reason, hiding the machine !!

 

Conclusion: do not try to return a value in finally. This may lead to unexpected logic errors. finally is used to release resources !!

 

Reference ox blog: http://blog.csdn.net/z69183787/article/details/61923256

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.