Error handling with Python |
|
Release 9.3
Last modified June 3, 2010 |
![]() ![]() ![]() Print all topics in : "Accessing tools within a geoprocessing script" |
Note:
This topic was updated for 9.3.1.
Errors happen. Writing scripts that expect and handle errors can save you a lot of time and frustration. When a tool writes an error message, the geoprocessing object generates a system error, or exception. In Python, you can provide a variety of structures and methods that can handle exceptions. Of course, a script can fail more many other reasons that are not specifically related to a geoprocessing tool; these too need to be caught and dealt with in an appropriate manner. The following sections offer a few techniques that introduce the basics of Python exception handling.
Geoprocessing tool errors are accompanied by a six-digit code. These ID codes have been documented to provide additional information on their cause and how they can be dealt with.
Learn more about creating and debugging geoprocessing scripts
Learn more about script tools
A try/except statement can be used to wrap entire programs or just particular portions of code to trap and identify errors. If an error occurs within the try statement, an exception is raised, and the code under the except statement is then executed. Using a simple except statement is the most basic form of error handling.
In the following code, Buffer fails because the required Distance parameter has not been used. Instead of failing without explanation, the except statement is used to trap the error, then fetch and print the error message generated by Buffer. Note that the except block is only executed if Buffer returns an error.
try: gp.buffer_analysis("c:/transport/roads.shp", "c:/transport/roads_buffer.shp") except: print "Error" print gp.getmessage(2)
The previous example dealt with handling an exception that occurred in the code; in some cases, it may be necessary to create exceptions yourself. A raise statement can be used for this purpose. In the following code, a raise statement is used when an input feature class has been identified as having no features. This is not strictly an error but is a condition that the code can be used to guard against.
import arcgisscripting import os gp = arcgisscripting.create(9.3) gp.overwriteoutput = 1 fc = gp.GetParameterAsText(0) try: # Check that the input has features # if gp.getcount(fc) > 0: gp.featuretopolygon(fc, os.path.dirname(fc) + os.sep + "out_poly.shp") else: raise "no features" except "no features": # The input has no features # print fc + " has 0 features." except: # By default any other errors will be caught here # print gp.getmessage(2)
In larger, more complex scripts, it can be difficult to determine the precise location of an error. Python's sys and traceback modules can be used together to isolate the exact location and cause of the error, identifying the cause of an error more accurately and saving you valuable debugging time.
In addition, not all errors are the same, and in many cases you will want to handle different types of errors in different ways. For instance, in the following example, the code handles geoprocessing tool errors differently from all other types of errors.
# Import the required modules # import arcgisscripting import sys import traceback gp = arcgisscripting.create() try: #-------------------------- # Your code goes here # # See the table below for examples #-------------------------- except arcgisscripting.ExecuteError: # Get the geoprocessing error messages # msgs = gp.GetMessage(0) msgs += gp.GetMessages(2) # Return gp error messages for use with a script tool # gp.AddError(msgs) # Print gp error messages for use in Python/PythonWin # print msgs except: # Get the traceback object # tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] # Concatenate information together concerning the error into a # message string # pymsg = tbinfo + "\n" + str(sys.exc_type)+ ": " + str(sys.exc_value) # Return python error messages for use with a script tool # gp.AddError(pymsg) # Print Python error messages for use in Python/PythonWin # print pymsg
Your code | Resulting error |
gp.getcount("") |
Failed to execute. Parameters are not valid. ERROR 000735: Input Rows: Value is required Failed to execute (GetCount). |
x = "a" + 1 |
x = "a" + 1 <type 'exceptions.TypeError'>: cannot concatenate 'str' and 'int' objects |
float("a text string") |
float("a text string") <type 'exceptions.ValueError'>: invalid literal for float(): a text string |
# Import the required modules # import win32com.client import pywintypes import sys import traceback gp = win32com.client.Dispatch("esriGeoprocessing.GpDispatch.1") try: #-------------------------- # Your code goes here #-------------------------- except pywintypes.com_error: # Get the geoprocessing error messages # msgs = gp.GetMessage(0) msgs += gp.GetMessages(2) # Return gp error messages for use with a script tool # gp.AddError(msgs) # Print gp error messages for use in Python/PythonWin # print msgs except: # Get the traceback object # tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] # Concatenate information together concerning the error into a # message string # pymsg = tbinfo + "\n" + str(sys.exc_type)+ ": " + str(sys.exc_value) # Return python error messages for use with a script tool # gp.AddError(pymsg) # Print Python error messages for use in Python/PythonWin # print pymsg