‘break’ or ‘return’ statement in finally¶
ID: py/exit-from-finallyKind: problemSecurity severity: Severity: warningPrecision: mediumTags: - quality - reliability - error-handling - correctness - external/cwe/cwe-584Query suites: - python-security-and-quality.qls
Click to see the query in the CodeQL repository
When abreak orreturn statement is used in afinally block this causes thetry-finally block to exit immediately discarding the exception. This is unlikely to be the intention of the developer and makes the code more difficult to read.
Recommendation¶
Either move thebreak orreturn statement to immediately after thefinally block or use an explicitexcept block to handle the exception.
These modifications are behavior changing so you must take care to ensure that the resulting behavior is correct.
References¶
Python Language Reference: The try statement, The break statement, The return statement.
Common Weakness Enumeration:CWE-584.