try:
something here
except:
print('the whatever error occurred.')
如何在except:
块中打印错误/异常?
发布于 2009-09-27 12:19:27
对于Python 2.6及更高版本和Python 3.x:
except Exception as e: print(e)
对于Python 2.5和更早版本,请使用:
except Exception,e: print str(e)
发布于 2009-09-27 12:25:49
traceback
模块为formatting and printing exceptions及其回溯提供了方法,例如,这将像默认处理程序一样打印异常:
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
发布于 2009-09-27 11:56:31
如果你想传递错误字符串,这里有一个来自Errors and Exceptions (Python2.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
https://stackoverflow.com/questions/1483429
复制相似问题