Python Try/except: Showing The Cause Of The Error After Displaying My Variables
I'm not even sure what the right words are to search for. I want to display parts of the error object in an except block (similar to the err object in VBScript, which has Err.Numbe
Solution 1:
try:
1 / 0
except Exceptionas e:
print(e)
Solution 2:
If you're expecting a DivideByZero error, you can catch that particular error
import traceback
try:
x = 5
y = 0print x/y
except ZeroDivisionError:
print"Error Dividing %d/%d" % (x,y)
traceback.print_exc()
except:
print"A non-ZeroDivisionError occurred"
You can manually get the line number and other information by calling traceback.print_exc()
Solution 3:
The string value of the exception object will give you the reason. The traceback
module will allow you access to the full traceback.
Solution 4:
A better approach is to make use of the standard Python Logging module.
import sys, traceback, logging
logging.basicConfig(level=logging.ERROR)
try:
x = 0y = 1
z = y / x
z = z + 1print"z=%d" % (z)
except:
logging.exception("Values at Exception: x=%d y=%d " % (x,y))
This produces the following output:
ERROR:root:Values at Exception: x=0 y=1
Traceback (most recent call last):
File "py_exceptions.py", line 8, in <module>
z = y / x
ZeroDivisionError:integer division or modulo by zero
The advantage of using the logging module is that you have access to all the fancy log handlers (syslog, email, rotating file log), which is handy if you want your exception to be logged to multiple destinations.
Solution 5:
In other words,
try:
1/0
except Exceptionas e:
print e
You can get the details in the manual pages linked by Ignacio in his response.
Post a Comment for "Python Try/except: Showing The Cause Of The Error After Displaying My Variables"