16.8.10

Exception Handling in ArcGIS Python

When writing python scripts, it is very important to add some basic exception handling so you're not pulling your hair out when a script doesn't work.

Recently I was running a geometry simplification script I've been using for about two years. I had never had a problem with it, but suddenly I started ERROR 999999: Error executing function. This error is basically ArcGIS saying "I have no idea what happened". Man I was bummmin...no lines numbers...no idea why after so long I had a problem. Was it the data? Well, yes...it turned out the Shape field was named 'Shape_' instead of 'Shape'.

To find the error, I wrapped the script inside a try/except block and used two functions in my helper class:


def reportGPErrors(self, geoprocessor):
    '''
    reports any geoprocessing related errors
    '''
    gpmsgs = geoprocessor.GetMessage(0)
    gpmsgs += geoprocessor.GetMessages(2)
    geoprocessor.AddError(gpmsgs)
    print gpmsgs

def reportSysErrors(self, geoprocessor):
    '''
    reports python system related errors
    '''
    tb = sys.exc_info()[2]
    tbinfo = traceback.format_tb(tb)[0]
    pymsg = "PYTHON ERRORS:\nTraceback Info:\n"
    pymsg += tbinfo + "\n"
    pymsg += "Error Info:\n" + str(sys.exc_type) + ": "
    pymsg += str(sys.exc_value) + "\n"
    geoprocessor.AddError(pymsg)
    print pymsg


Both of the functions take a geoprocessor, which gives the ability to print to both the python console and the ArcGIS message window.

To implement these function in geoprocessing scripts, simply import helpers class, and place a call to these function in the try/except block:


from helpers import Helpers
oHelpers = Helpers()
gp = oHelpers.createGeoprocessor()

try:

    code...code...code

except:
    oHelpers.reportGPErrors(gp)
    oHelpers.reportSysErrors(gp)

No comments:

Post a Comment