【问题标题】:Print error type, error statement and own statement打印错误类型、错误语句和自己的语句
【发布时间】:2015-06-29 18:32:36
【问题描述】:

我想尝试一个语句,如果有错误,我希望它打印它收到的原始错误,但还要添加我自己的语句。

我一直在寻找这个答案,找到了几乎完整的东西here

以下代码几乎完成了我想要的所有工作(我使用的是 Python 2,所以它可以工作):

except Exception, e: 
    print str(e)

这样我可以打印错误消息和我想要的字符串,但是它不会打印错误类型(IOErrorNameError 等)。我想要的是让它打印出与通常情况完全相同的消息(所以ErrorType: ErrorString)加上我自己的声明。

【问题讨论】:

    标签: python python-2.x


    【解决方案1】:

    如果要打印异常信息,可以使用traceback模块:

    import traceback
    try:
        infinity = 1 / 0
    except Exception as e:
        print "PREAMBLE"
        traceback.print_exc()
        print "POSTAMBLE, I guess"
    

    这给了你:

    PREAMBLE
    Traceback (most recent call last):
      File "testprog.py", line 3, in <module>
        infinity = 1 / 0
    ZeroDivisionError: integer division or modulo by zero
    POSTAMBLE, I guess
    

    您也可以在不使用traceback 的情况下重新抛出异常,但是,由于这是一个抛出的异常,因此之后您无法执行任何操作:

    try:
        infinity = 1 / 0
    except Exception as e:
        print "PREAMBLE"
        raise
        print "POSTAMBLE, I guess"
    

    注意在这种情况下缺少POSTAMBLE

    PREAMBLE
    Traceback (most recent call last):
      File "testprog.py", line 2, in <module>
        infinity = 1 / 0
    ZeroDivisionError: integer division or modulo by zero
    

    【讨论】:

    • 啊,这确实更容易。我认为我的理想情况是如果我可以在错误消息后面打印我自己的语句,因为这样更具可读性。但我也想到,加注后,你什么也做不了。因此,除非有一种简单的方法可以提取整个错误消息(包括回溯),否则我认为您的回答是我能做的最好的:)谢谢!
    • 请注意:由于您现在没有在 except 子句中使用错误字符串 'e',您现在不能将“except Exception as e:”更改为“except:”吗?
    【解决方案2】:

    来自python docs

    try:
        raise Exception('spam', 'eggs')
    except Exception as inst:
        print(type(inst))    # the exception instance
        print(inst.args)     # arguments stored in .args
        print(inst)          # __str__ allows args to be printed directly,
    

    将被打印:

    <type 'exceptions.Exception'>
    ('spam', 'eggs')
    ('spam', 'eggs')
    

    【讨论】:

      猜你喜欢
      • 2016-08-16
      • 1970-01-01
      • 2017-03-31
      • 1970-01-01
      • 2011-11-26
      • 1970-01-01
      • 2014-02-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多