我如何打印错误/异常在except:块?

try:
    ...
except:
    print(exception)

当前回答

在Python 2.6或更高版本中,它更简洁:

except Exception as e: print(e)

在较旧的版本中,它仍然是相当可读的:

except Exception, e: print e

其他回答

如果你想传递错误字符串,这里有一个来自错误和异常(Python 2.6)的例子

>>> 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 printed directly
...    x, y = inst          # __getitem__ allows args to be unpacked directly
...    print 'x =', x
...    print 'y =', y
...
<type 'exceptions.Exception'>
('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs

在Python 2.6或更高版本中,它更简洁:

except Exception as e: print(e)

在较旧的版本中,它仍然是相当可读的:

except Exception, e: print e

对于Python 2.6及更高版本和Python 3.x:

except Exception as e: print(e)

对于Python 2.5及更早版本,使用:

except Exception,e: print str(e)

在这里展开“except Exception as e:”的解决方案是一个很好的一行,其中包括一些额外的信息,如错误的类型和发生的位置。


try:
    1/0
except Exception as e:
    print(f"{type(e).__name__} at line {e.__traceback__.tb_lineno} of {__file__}: {e}")

输出:

ZeroDivisionError at line 48 of /Users/.../script.py: division by zero

traceback模块提供了格式化和打印异常及其回溯信息的方法,例如,这将像默认处理程序一样打印异常:

import traceback

try:
    1/0
except Exception:
    traceback.print_exc()

输出:

Traceback (most recent call last):
  File "C:\scripts\divide_by_zero.py", line 4, in <module>
    1/0
ZeroDivisionError: division by zero