How to print an exception in Python?
1 2 3 4 | try: something here except: print 'the whatever error occurred.' |
如何在我的
对于python 2.6及更高版本和python 3.x:
1 | except Exception as e: print(e) |
对于python 2.5及更早版本,请使用:
1 | except Exception,e: print str(e) |
1 2 3 4 5 6 | import traceback try: 1/0 except Exception: traceback.print_exc() |
输出:
1 2 3 4 | Traceback (most recent call last): File"C:\scripts\divide_by_zero.py", line 4, in <module> 1/0 ZeroDivisionError: division by zero |
在python 2.6或更高版本中,它有点干净:
1 | except Exception as e: print(e) |
在旧版本中,它仍然非常可读:
1 | except Exception, e: print e |
如果您想传递错误字符串,下面是一个来自错误和异常的示例(python 2.6)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | >>> 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 |
(我本来打算留下这句话作为对@jldupont答案的评论,但我没有足够的声誉。)
我在其他地方也看到过类似@jldupont的答案。fwiw,我认为重要的是要注意:
1 2 | except Exception as e: print(e) |
默认情况下将错误输出打印到
1 2 | except Exception as e: print(e, file=sys.stderr) |
(请注意,您必须使用
我还没有像cat plus的答案那样使用
如果您想这样做,可以使用断言语句来执行一个线性错误引发。这将帮助您编写静态的可修复代码并尽早检查错误。
1 | assert type(A) is type(""),"requires a string" |