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
Avoid using finally statement in return block. If used, it will swallow the exception raised but not handled in above try except block.
Violation Code Sample
>>> def experiment():
>>> try:
>>> x = 2/0
>>> except:
>>> logging.debug("Not possible")
>>> finally:
>>> logging.debug("Division")
>>> return
Fixed Code Sample
>>> def experiment():
>>> try:
>>> x = 2/0
>>> except:
>>> logging.debug("Not Possible")
>>> finally:
>>> logging.debug("Division")
>>> clean_up_code() #Return should not be used inside finally
Reference
CISQ OMG ASCMM-MNT-01
Related Technologies
Technical Criterion
PCI-DSS4-Requirement-6.2.4 - Software engineering techniques or other methods are defined and in use by software development personnel to prevent or mitigate common software attacks and related vulnerabilities
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.