PageRenderTime 22ms CodeModel.GetById 12ms app.highlight 8ms RepoModel.GetById 1ms app.codeStats 0ms

/source/error-handling.rst

https://github.com/chadcooper/argis-python-2013
ReStructuredText | 131 lines | 93 code | 38 blank | 0 comment | 0 complexity | 2f50a25c4a346f85b7182ca3b643c24e MD5 | raw file
  1Error handling
  2==============
  3
  4If you set it up from the beginning, it will make things much easier when 
  5testing your code.
  6
  7Simple error handling
  8---------------------
  9
 10The basics of error handling are this:
 11
 12.. code-block:: python
 13
 14   try:
 15       do something...
 16   except:
 17       handle error...
 18   finally:
 19       clean up...
 20
 21In the ArcMap Python prompt, type this:
 22
 23.. code-block:: python
 24
 25   arcpy.Buffer_analysis("Observer")
 26   
 27And you'll get something messy like:
 28
 29.. code-block:: python
 30
 31   Runtime error  Traceback (most recent call last):   File "<string>", 
 32   line 1, in <module>   File "c:\program files (x86)\arcgis\desktop10.1\arcpy\
 33   arcpy\analysis.py", line 687, in Buffer     raise e ExecuteError: ERROR 
 34   000732: Input Features: Dataset Observer does not exist or is not supported 
 35   ERROR 000735: Distance [value or field]: Value is required 
 36   
 37Now try this:
 38
 39.. code-block:: python
 40
 41   try:
 42       arcpy.Buffer_analysis("Observer")
 43   except Exception as e:
 44       print e.message
 45   
 46And you get:
 47
 48.. code-block:: python
 49
 50   ERROR 000732: Input Features: Dataset Observer does not exist or is not supported
 51   ERROR 000735: Distance [value or field]: Value is required
 52
 53   
 54Cleaning up with ``try/except/finally``
 55---------------------------------------  
 56
 57Sometimes you want to clean up when something goes south, the ``finally`` 
 58clause lets you do that:
 59
 60.. code-block:: python
 61
 62   try:
 63       if arcpy.CheckExtension("3D") == "Available":
 64           arcpy.CheckOutExtension("3D")
 65           arcpy.Slope_3d("Magic.gdb/NWA10mNED", "Magic.gdb/SlopeNWA")
 66   except Exception as e:
 67       print e.message
 68       print arcpy.GetMessages(2)
 69   finally:
 70       # Check in the 3D Analyst extension
 71       arcpy.CheckInExtension("3D") 
 72       
 73And you get:
 74
 75.. code-block:: python
 76   
 77   ERROR 000865: Input raster: Magic.gdb/NWA10mNED does not exist.
 78   
 79.. note:: 
 80
 81   Using ``finally`` also works well for closing database connections.
 82   
 83Getting stack info with ``traceback``
 84-------------------------------------
 85
 86The ``traceback`` module provides a standard interface to extract, format and 
 87print stack traces of Python programs. It exactly mimics the behavior of the 
 88Python interpreter when it prints a stack trace. Basically, it gives you the 
 89most info you can get related to your error(s):
 90
 91Paste this into a IDLE script and run it:
 92
 93.. code-block:: python
 94
 95   import sys
 96   import traceback
 97
 98   try:
 99       # Your code goes here
100       float("a string")
101   except:
102       # Get the traceback object
103       tb = sys.exc_info()[2]
104       tbinfo = traceback.format_tb(tb)[0]
105       # Concatenate information together concerning the error into a message string
106       #   tbinfo: where error occurred
107       #   sys.exc_info: 3-tuple of type, value, traceback
108       pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_info()[1])
109       msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages(2) + "\n"
110       # Return python error messages for use in script tool or Python Window
111       arcpy.AddError(pymsg)
112       if arcpy.GetMessages(2):
113           arcpy.AddError(msgs)
114           print msgs
115       # Print Python error messages for use in Python / Python Window
116       print pymsg + "\n"
117       
118This tells you **exactly** where your error is occurring:
119
120.. code-block:: python
121
122   >>> 
123   PYTHON ERRORS:
124   Traceback info:
125     File "C:/Users/class5user/ar-gis-python/crap.py", line 7, in <module>
126       float("a string")
127
128   Error Info:
129   could not convert string to float: a string
130
131   >>>