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.