跳到内容

finally 语句中的跳转语句 (B012)

源自 flake8-bugbear linter。

作用

检查 finally 代码块中是否有 breakcontinuereturn 语句。

为什么这不好?

finally 代码块中使用 breakcontinuereturn 语句可能会导致异常被静默处理。

无论是否引发异常,finally 代码块都会执行。如果在 finally 代码块中遇到 breakcontinuereturn 语句,则在 tryexcept 代码块中引发的任何异常都将被静默处理。

示例

def speed(distance, time):
    try:
        return distance / time
    except ZeroDivisionError:
        raise ValueError("Time cannot be zero")
    finally:
        return 299792458  # `ValueError` is silenced

建议改为

def speed(distance, time):
    try:
        return distance / time
    except ZeroDivisionError:
        raise ValueError("Time cannot be zero")

参考