rgthurau

How to keep missing fields from crashing my code?

Discussion created by rgthurau on Jun 12, 2012
Latest reply on Aug 21, 2014 by gmbacon
Hi,
I have a very helpful code I use to run metrics between land cover and a bunch of assessment boundary feature classes using tabulate area. I put my land cover classes in a list and the field names that are calculated from the classes in another list. Update cursor fills in the rest.

The problem is, if I have an assessment boundary that does not intersect a land cover class, when update cursor goes to calculate the field from the class value, it crashes the code.

I will paste a sample code:

ClassList = ["Forest", "Vegetation"]
FieldList = ["Land_Acres","Forest_Acres", "Forest_Percent", "Veg_Acres", "Veg_Percent"]

m2ac = 0.0002471054

FcList = arcpy.ListFeatureClasses("*", "")   
for fc in FcList:
    areaTab1 = "Metrics_" + os.path.basename(fc)
    for field in FieldList:
        arcpy.AddField_management(fc, field, "DOUBLE")
    TabulateArea(fc, "GID", LC, "Class", areaTab1 , 1) #"UTC_Metrics_" + os.path.basename(fc)
    arcpy.JoinField_management(fc, "GID", areaTab1, "GID", ClassList)#"trees11_tab_" + os.path.basename(fc)
    rows = arcpy.UpdateCursor(fc)
    print str(fc)
    for row in rows:  
        row.setValue(FieldList[0], (row.Shape_Area * m2ac))#Total Acres
        rows.updateRow(row)
        row.setValue(FieldList[1], row.getValue(ClassList[0]) * m2ac) #Forest Acres
        rows.updateRow(row)
        row.setValue(FieldList[2], (row.getValue(FieldList[1]) / row.Land_Acres) * 100) #Forest Percent
        rows.updateRow(row)
        row.setValue(FieldList[3], row.getValue(ClassList[1]) * m2ac) #Veg Acres
        rows.updateRow(row)
        row.setValue(FieldList[4], (row.getValue(FieldList[3]) / row.Land_Acres) * 100) #Veg Percent
        rows.updateRow(row)
    del row
    del rows


So, this code runs great, unless one of the feature classes does not intersect with one of the land cover classes. Then, when the code calls the ClassList for that value, the code will crash in two spots:
1. At the joinfield, where it looking for all classes from the class list to join
2. In the update cursor when it calls the class name to calculate the fields.

Is there  a good way to make the code just skip the value rather than crashing the code?

Thanks

Rich
#

Outcomes