Unreachableexcept block¶
ID: py/unreachable-exceptKind: problemSecurity severity: Severity: errorPrecision: very-highTags: - quality - reliability - error-handling - external/cwe/cwe-561Query suites: - python-security-and-quality.qls
Click to see the query in the CodeQL repository
When handling an exception, Python searches the except blocks in source code order until it finds a matchingexcept block for the exception. An except block,exceptE:, specifies a classE and will match any exception that is an instance ofE.
If a more general except block precedes a more specific except block, then the more general block is always executed and the more specific block is never executed. An except block,exceptA:, is more general than another except block,exceptB:, ifA is a super class ofB.
For example:exceptException: is more general thanexceptError: asException is a super class ofError.
Recommendation¶
Reorganize theexcept blocks so that the more specificexcept is defined first. Alternatively, if the more specificexcept block is no longer required, then it should be deleted.
Example¶
In the following example, theexceptException: will handleAttributeError preventing the subsequent handler from ever executing.
defincorrect_except_order(val):try:val.attrexceptException:print("Exception")exceptAttributeError:print("AttributeError")
References¶
Python Language Reference:The try statement,Exceptions.
Common Weakness Enumeration:CWE-561.