Error handling in script tools

The basics of handling Python errors are covered in the topic Error handling with Python. The Python.org document Errors and Exceptions has more detailed information.

Getting error messages from a result object

A quick word about the Result object, shown below:

result = arcpy.GetCount_management("c:/data/rivers.shp")

If the call to GetCount raises an exception, the result object is null. This means you cannot retrieve error messages from the result object.

import arcpy
try:
    result = arcpy.GetCount_management("c:/data/rivers.shp")

# Return GEOPROCESSING specific errors
# (this method is INCORRECT!)
except:
    arcpy.AddError(result.getMessages(2))

The above code fails with the message "name 'result' is not defined". This is because the result object could not be created due to the tool's failure. Since the result object is not created, a Python error is raised when trying to use the getMessages method.

NoteNote:

A result object created by calling a geoprocessing service on ArcGIS Server is created even with a tool failure. A result object only fails to be created when a tool is run locally and it raises an error. For more information about using the result object, see Getting results from a geoprocessing tool.

Using AddReturnMessage to preserve links to error codes

Geoprocessing error numbers shown in the progress dialog box are hyperlinks to a help page that further describes the error. To enable hyperlinks for errors in your script, use the AddReturnMessage function instead of the AddError function, as follows:

import arcpy
try:    
    result = arcpy.GetCount_management("c:/data/rivers.shp")

except:    
    # Return Geoprocessing tool specific errors
    #
    for msg in range(0, arcpy.GetMessageCount()):
        if arcpy.GetSeverity(msg) == 2:
            arcpy.AddReturnMessage(msg)

4/14/2011