Corejava_ do not use the return keyword in a finally block

Source: Internet
Author: User
Tags finally block

This afternoon when the code was submitted, I saw one of the checklist, checking to see if a return statement was used in the finally block. After all, for several years, suddenly unexpectedly forget, why?

Hurriedly hands, wrote a demo, suddenly dawned:

public class Testfinally {public    int getaddresult (int. X,int y) {        try{            System.out.println ("before return in Try section. ");            return x+y;        } finally{            System.out.println ("Before return in the finally section.");            return x*y;        }    }    public static void Main (string[] args) {        System.out.println (new testfinally (). Getaddresult (Ten));}    }
The results of the above program are as follows:
Before return in a try section.
Before return in the finally section.
200
It dawned on the original Java implementation mechanism is to call the try code block return before the code will be executed finally, so that finally return will end the current method, return an incorrect value, the best practice or, Only a small amount of resources need to be released, only to use Finally, do not throw a brain into the finally inside to deal with, the other throw to Java garbage collection mechanism to deal with.

Corejava_ do not use the return keyword in a finally block

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.