Improve the quality of your Java code: Do not process returned values in finally blocks.

Source: Internet
Author: User

I. Analysis
When processing return values in finally, the code looks perfect and complies with logic, but logical errors will occur when executed, the most important thing is that finally is used to handle the final handling of exceptions. Once a return statement is added, the complexity of the program will be greatly increased, and there will be some highly concealed errors.
Similar to the return Statement, System. exit (0) or Runtime. getRuntime (). exit (0) may also generate many false positives in the Exception Code block.
Ii. Scenarios
The Code is as follows:

Public static void main (String [] args) {try {doStuff (-1); doStuff (100);} catch (Exception e) {System. out. println ("This will never arrive");} // This method throws the checked exception public static int doStuff (int _ p) throws Exception {try {if (_ p <0) {throw new DataFormatException ("Data Format error");} else {return _ p ;}} catch (Exception e) {// throw e;} finally {return-1 ;}}

1. overwrite the return value in the try code block
When doStuff (-1) is executed, the doStuff method generates a DataFormatException. The catch Block directly throws the exception after capturing the exception. After the code block is executed to the finally code block, the return value is reset, the result is-1, and the returned value is returned first. When finally is executed, the returned value is reset.
2. Shielding exceptions

Iii. Suggestions
Do not use return statements in finally code blocks.

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.