跳到内容

尝试-考虑-else (TRY300)

源自 tryceratops linter。

作用

检查try块中的return语句。

为什么这不好?

try-except语句有一个else子句,用于在未引发异常时运行的代码。try块中的返回语句可能会表现出令人困惑或不希望的行为,例如被exceptfinally块中的控制流覆盖,或无意中抑制异常。

示例

import logging


def reciprocal(n):
    try:
        rec = 1 / n
        print(f"reciprocal of {n} is {rec}")
        return rec
    except ZeroDivisionError:
        logging.exception("Exception occurred")

建议改为

import logging


def reciprocal(n):
    try:
        rec = 1 / n
    except ZeroDivisionError:
        logging.exception("Exception occurred")
    else:
        print(f"reciprocal of {n} is {rec}")
        return rec

参考