Eclipse Yellow Warning (finally block does not complete normally), it is not recommended to use the return statement in finally

Source: Internet
Author: User
Tags finally block



By writing the following code in Eclipse, Eclipse gives a yellow warning: Finally block does not complete normally.


public class Test
{
    public static void main(String[] args)
    {
        System.out.println(m1(null));
    }

    public static String m1(String name)
    {
        try
        {
            name.length();
        }
        finally
        {
            return name + "_test";
        }
    }
}


This code runs the result: the console prints the null_test, without throwing a null pointer exception (swallowed by the JVM). The program has allowed exceptions, but is pocketed by the JVM, which is obviously bad practice. It is not recommended to use the return statement in a finally block for the following reasons:



1. The return statement in the finally block overwrites the previous return statement (the try block, the return statement in the Catch block), which makes it difficult to determine the return result of the method and easily draws the wrong conclusion.



2. If the finally block contains a return statement, even if the preceding try or catch block throws an exception, the statement calling the method does not get the exception that the catch block re-throws, but instead gets the return value of the finally block and does not catch the exception.





In short, using return in finally is a bad programming practice and should be avoided. For the return value problem of using return in try-catch-finally, take a look at http://www.cnblogs.com/aigongsi/archive/2012/04/19/2457735.html this blog, A number of cases are listed, and the analysis is very detailed. Even experienced programmers may mistakenly judge the method to return the results, and do not believe you can try.


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.