繁体   English   中英

如何在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

但是它仍然一直在引发错误。 有没有办法实现我的想象?

谢谢

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]

另请参见有关BaseException.args文档

您可以像这样捕获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]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM