views:

116

answers:

2

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

+8  A: 

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.

The MYYN
wow. i really fail. thanks!
calccrypto
If you want to re-raise the exception (ie. halt execution, etc), use `raise e` or just `raise`.
detly
+2  A: 

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
Michał Niklas
From http://www.python.org/dev/peps/pep-0008/: "When catching exceptions, mention specific exceptions whenever possible instead of using a bare 'except:' clause. [...] A bare 'except:' clause will catch SystemExit and KeyboardInterrupt exceptions, making it harder to interrupt a program with Control-C, and can disguise other problems. If you want to catch all exceptions that signal program errors, use 'except Exception:'."
Walter
OK. Added `Exception` to `except`.
Michał Niklas