我怎样才能在 Python 中只捕获某种类型的 ValueError?

How can I catch only a certain type of ValueError in Python?

我处理数据,对于某些示例,数据有问题。 Python 提出一个

ValueError: Residuals are not finite in the initial point.

是否有可能仅通过消息 "Residuals are not finite in the initial point." 捕获值错误? 我试过了:

try:
    [code that could raise the error]
except Exception as e:
    if e=='ValueError(\'Residuals are not finite in the initial point.\')':
        [do stuff I want when the Residuals are not finite]
    else:
        raise e

但还是一直报错。有没有办法实现我想象的?

谢谢

您可以像这样捕获 ValueError 异常:

try:

    #[code that could raise the error]

except ValueError as e:

    print("Residuals are not finite in the initial point. ...")
    #[do stuff I want when the Residuals are not finite]
try:
    [code that could raise the error]
except ValueError as e:
    if len(e.args) > 0 and e.args[0] == 'Residuals are not finite in the initial point.':
        [do stuff I want when the Residuals are not finite]
    else:
        raise e

您可能需要检查 e.args[0] 是否完全包含此字符串(引发错误并打印 e.args[0]

另见 documentation about BaseException.args