跳到内容

raise-vanilla-args (TRY003)

源自 tryceratops linter。

作用

检查未在异常类本身中定义的过长异常消息。

为什么这不好?

通过在 raise 位置格式化异常消息,异常类的可重用性降低,并且现在可能会根据引发位置引发不一致的消息。

如果异常消息改为在异常类中定义,则在所有 raise 调用中都将保持一致。

此规则不适用于某些内置异常,这些异常通常会引发消息并且子类化是不寻常的,例如 NotImplementedError

示例

class CantBeNegative(Exception):
    pass


def foo(x):
    if x < 0:
        raise CantBeNegative(f"{x} is negative")

建议改为

class CantBeNegative(Exception):
    def __init__(self, number):
        super().__init__(f"{number} is negative")


def foo(x):
    if x < 0:
        raise CantBeNegative(x)