Rule Definition
Care must be taken if completion of a try-catch block occurs as a result of executing a return. If a finally block also returns a value, then that return supersedes any previous return in the try-catch block. Also, if an exception was thrown in the try or catch blocks that was not caught, then execution of a return in the finally block prevents the exception from being thrown to the caller (because it is not possible for the caller to simultaneously evaluate the return and catch the exception). This is also valid for break or continue instructions.
Remediation
Remove the return statement from the finally block.
Violation Code Sample
f = 0;
try {
try {
f = open(filename);
text = f.read();
}
catch(err) {
}
finally {
if (f) {
f.close();
return;
}
}
Fixed Code Sample
let f = 0;
let success = false; // a variable to return the status
try {
f = open(filename);
text = f.read();
success = true;
}
catch(err) {
logger.error("Cannot read", filename, err);
success = false;
}
finally {
if (f) {
f.close();
}
return success;
}
Reference
OWASP
http://www.owasp.org/index.php/Return_Inside_Finally_Block
CWE
http://cwe.mitre.org/data/definitions/584.html
CISQ OMG
ASCMM-MNT-01 - Control Flow Transfer Control Element outside Switch Block
Related Technologies
Technical Criterion
Programming Practices - Error and Exception Handling
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.