在Python中打印异常,而不是提高它们

Ben*_*ner 3 python exception-handling exception

我想捕获一个Python异常并打印它而不是重新提升它.例如:

def f(x):
    try:
        return 1/x
    except:
        print <exception_that_was_raised>   
Run Code Online (Sandbox Code Playgroud)

这应该做:

>>> f(0)
'ZeroDivisionError'
Run Code Online (Sandbox Code Playgroud)

没有例外被提出.

有没有办法做到这一点,除了在巨大的try-except-except ...... except子句中列出每个可能的异常?

Ash*_*ary 9

使用message异常的属性或者e.__class__.__name__如果您想要Base异常类的名称,即ZeroDivisionError'在您的情况下

In [30]: def f(x):
        try:
                return 1/x
        except Exception as e:
            print e.message
   ....:         

In [31]: f(2)
Out[31]: 0

In [32]: f(0)
integer division or modulo by zero
Run Code Online (Sandbox Code Playgroud)

在python 3.x中,该message属性已被删除,因此您只需使用print(e)e.args[0]在那里,并e.__class__.__name__保持相同.