无法到达的“except”块¶
ID: py/unreachable-except
Kind: problem
Security severity:
Severity: error
Precision: very-high
Tags:
- reliability
- maintainability
- external/cwe/cwe-561
Query suites:
- python-security-and-quality.qls
在处理异常时,Python 按源代码顺序搜索 except 块,直到找到与异常匹配的 except 块。Except 块 except E: 指定一个类 E,并将匹配任何 E 的实例的异常。
如果更一般的 except 块位于更具体的 except 块之前,那么更一般的块始终会被执行,而更具体的块永远不会被执行。Except 块 except A: 比另一个 except 块 except B: 更一般,如果 A 是 B 的超类。
例如:except Exception: 比 except Error: 更一般,因为 Exception 是 Error 的超类。
建议¶
重新组织 except 块,使更具体的 except 首先定义。或者,如果更具体的 except 块不再需要,则应将其删除。
示例¶
在此示例中,except Exception: 将处理 AttributeError,从而阻止后续处理程序执行。
def incorrect_except_order(val):
try:
val.attr
except Exception:
print ("Exception")
except AttributeError:
print ("AttributeError")
参考资料¶
Python 语言参考:The try statement,Exceptions.
通用弱点枚举:CWE-561.