开发者

How to show why "try" failed in python

is there anyway to show why a "try" failed, and skipped to "except", without writing out all the possible errors by hand, and without ending the program?

example:

try:
    1/0
except:
    someway to show 
    "Traceback (most recent call last):
       File "<pyshell#0>", line 1, in <module>
         1/0
    ZeroDivisionError: integer division or modulo by zero"

i dont want to doif:print error 1, elif: print erro开发者_开发百科r 2, elif: etc.... i want to see the error that would be shown had try not been there


Try:

>>> try:
...     1/0
... except Exception, e:
...    print e
... 
integer division or modulo by zero

There are other syntactical variants, e.g.:

>>> try:
...     1/0
... except Exception as e:
...    print e
... 
integer division or modulo by zero

More information can be found in the errors tutorial.


I often use traceback to log such exception to log or show on stderr:

import traceback
import sys

try:
    print 1/0
except Exception:
    s = traceback.format_exc()
    serr = "there were errors:\n%s\n" % (s)
    sys.stderr.write(serr) 

Output will show info about line is source where exception occured:

there were errors:
Traceback (most recent call last):
  File "c:\test\ex.py", line 5, in <module>
    print 1/0
ZeroDivisionError: integer division or modulo by zero
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜