【问题标题】:Python: When catching a generic (any) exception, how do I store the exception name in a variable?Python:捕获通用(任何)异常时,如何将异常名称存储在变量中?
【发布时间】:2018-07-03 22:30:25
【问题描述】:

我知道我可以使用以下语法将异常名称存储在变量中:

try:
    code
except TypeError as e:
    logger.error(e)
except NameError as e:
    logger.error(e)

我如何对通用的except: 消息执行相同的操作?我认为这(这是一般想法)行不通:

try:
    code
except as e:
    logger.error(e)

【问题讨论】:

  • 永远不要试图捕捉一个裸露的except,因为它甚至会停止使用 CTRL-C 捕捉流氓程序。

标签: python exception try-catch


【解决方案1】:

您可以使用 type(e).__name__ 来捕获您遇到的任何错误的名称,并使用 e.message 将消息作为普通变量访问。所有内置错误(indexError、TypeError 等)都是 Exception 类的子类,因此它们将被拾取。将其保存为名为 'err' 的变量:

try:
   code
except Exception as e:
   err = type(e).__name__
   message = e.message

这将使用内置的 __name__ 变量保存您遇到的基本 Python 类型 Exception 的任何异常的错误类型

【讨论】:

  • 我是否也应该像另一条评论所建议的那样捕获 BaseException(对于内置异常而不是用户定义的异常)?
  • 您可以在python docs 中更深入地了解它,但 Exception 将涵盖 BaseException 以及用户创建的错误,应将其创建为 Exception 对象。 TL;DR:异常将涵盖所有内置的非系统退出错误
【解决方案2】:

BaseException 是您能捕捉到的最广泛的类型:

try:
    # some code
except BaseException as e:
    logger.error(e)

【讨论】:

    【解决方案3】:

    你可以赶上Exception:

    import logging
    
    try:
        code
    except TypeError as e:
        logger.error(e)
    except NameError as e:
        logger.error(e)
    except Exception as e:
        logging.error(e)
    

    【讨论】:

    • 如果你以同样的方式处理它们,你不妨抓住Exception,因为它包括其他人。
    猜你喜欢
    • 2013-08-13
    • 1970-01-01
    • 2022-12-14
    • 2015-11-18
    • 2020-06-15
    • 2021-08-19
    • 2012-02-12
    • 2013-10-20
    • 2016-12-13
    相关资源
    最近更新 更多