Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 error 2, elif: etc.... i want to see the error that would be shown had try not been there

like image 631
calccrypto Avatar asked Jun 07 '10 10:06

calccrypto


2 Answers

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
like image 154
Michał Niklas Avatar answered Nov 05 '22 10:11

Michał Niklas


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.

like image 37
miku Avatar answered Nov 05 '22 12:11

miku