[Tutor] catching any exception?
BELSEY, Dylan
dylan.belsey@baesystems.com
Thu Nov 14 00:01:02 2002
Hi Lance,
I have been working on something similar to catch all the exceptions
from a python script file that the user creates. It initially checks for
some particular exception types that I know could be raised and the final
clause is a catch-all for any exceptions that are not accounted for such as
syntax errors in the script. It makes use of the "traceback" module,
obtains a trace of the latest exception and sends the info to an error
logger as a single line. From the code it is obvious that this is embedded
within a class and makes use of other objects, but I hope that the ideas and
logic are clear.
Anyway, I'm not sure how relevant it will be for you but I have
posted the code below. Hope you can make use of it.
Dylan.
PS: Using Python 2.1.1
# Code begins:
import sys, traceback, string
# Capture the latest stack trace for an exception.
# Use a function to avoid a circular reference problem in Python.
# Refer: http://www.python.org/doc/current/lib/module-sys.html
# for further information.
# INPUT: None.
# OUTPUT: List of strings containing the error.
def ObtainTrace(self):
# "Thread-safe" capture of the exception.
excType, excValue, excTraceback = sys.exc_info()
# Format the most recent stack trace and info. for exceptions.
Trace = traceback.format_exception(excType, excValue, excTraceback,
None)
# Delete the traceback object to avoid causing a circular reference
problem.
del excTraceback
return Trace
# Capture the exception if the script file is in error.
try:
execfile(self.ScriptFile)
except exceptions.TypeError, errMsg:
# Don't really need to specify the "exceptions" class in the line above.
# Handle this exception....
except: # For syntax and other errors in the file.
# Create the error message.
# Capture the latest exception.
TraceList = self.ObtainTrace()
# Extract important lines into a string.
# refer to traceback doco for more info here.
if len(TraceList) > 3:
lines = TraceList[2] + TraceList[3]
else:
lines = ''.join(TraceList) # Whole stack trace.
# Replace newlines with a full-stop and a space.
errMsg = string.replace(lines, '\n', '. ')
EMessage = """Exception in script file: %s"""%(errMsg)
# Send to the logger.
self.ErrorHandler.Capture(ErrorLogWindow.UI_SCRIPT_OP_ERROR, EMessage)
# Set the file path string to None so that the error does not repeat.
self.ScriptFile = None
# Code ends.