Masthead

Try Except Blocks

1. Adding Try/Except Blocks

The script we just wrote will work but it is missing some critical error checking. In the code below we've added "try" and "catch" blocks. These are part of the error, or "exception", handling in Python and it similar to the error handling in Java and JavaScript. The important point is that if any of the code within the "try" block generates an error, then the code in the "catch" block will be called. This makes error handling very easy as you don't have to worry about checking errors in every function, you do need to check errors in your "top-level" script. Try the following:

try:
    import arcpy

    # Check out the ArcGIS Spatial Analyst extension license
    arcpy.CheckOutExtension("Spatial")

    # Path to the data (you can also set a workspace instead), change this to point to your data
    InputPath="C:/Temp/"

    # run the aspect tool
    OutRaster=arcpy.sa.Aspect(InputPath+"Temp.img")

    # save to a TIFF file (try and GRID by removing the extention but it may not work)
    OutRaster.save(InputPath+"Aspect.img")

    print("Finished without an error")
    
except:
    print("An error occurred")
    print(arcpy.GetMessages())   

You can make the error handling as complex or as simple as your target users (who will be using the script) need. If only you are using the script then the code above is probably fine. However, if you are going to make this a tool that is distributed to others, you'll probably want to add additional "try-except" blocks to check where the error occurred. The code above could fail on the "import" if ArcGIS is not installed, on the "CheckOutExtension" call if the proper license is not available, on the "Aspect" call if the file is not available, and finally on the "save" if the file cannot be written. We'll touch on error checking like this again when we look at user interfaces.

© Copyright 2018 HSU - All rights reserved.