【问题标题】:How can I catch only a certain type of ValueError in Python?如何在 Python 中仅捕获某种类型的 ValueError?
【发布时间】:2019-06-12 13:35:53
【问题描述】:

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

ValueError:残差在初始点不是有限的。

是否有可能仅通过消息"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

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

谢谢

【问题讨论】:

    标签: python exception-handling try-catch valueerror raise


    【解决方案1】:

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

    【讨论】:

    • 这不能回答问题,因为可以出于多种原因抛出 ValueError。 MaxS 对带有问题中描述的消息的 ValueError 特别感兴趣。
    • 是的,但我想只捕捉那些显示我提到的消息的人。
    【解决方案2】:
    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

    【讨论】:

    • 为了完整起见,您可能需要引用docs,尤其是以“The except 子句可能”开头的段落。在尝试访问 e.args[0] 之前先检查 if len(e.args) 也可能是明智的,以防代码引发更多没有输入的 ValueErrors。
    • @Reti43 我已经增强了答案。谢谢。
    猜你喜欢
    • 2012-10-27
    • 2014-02-14
    • 2018-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-09
    • 1970-01-01
    相关资源
    最近更新 更多