Programming Week 3: Debugging and Handling Errors
In this week's lab, we practiced finding and correcting errors in Python scripts and catching exceptions using try-except statements. The first script prints the names of the fields in the attribute table for the parks.shp shapefile, and had a few syntax errors that I corrected.
Output from Script 1
The second script prints the spatial reference information and the layers for the project TravisCountyAustinTX.aprx. I got the error AttributeError: ‘module’ object has no attribute ‘mp', which I googled and learned that I was using Python 2.7.16 instead of Python 3.9.11, because I opened the script in regular IDLE instead of IDLE for ArcGIS Pro. You can see the different Python versions in the screenshots from script 1 (above, before I realized this mistake) and scripts 2 and 3 (below).
Output from Script 2
Output from Script 3
Script 3 Part A was supposed to print the name of the parks layer, make the layer visible, and turn on labels for the layer, then save the project. Part B prints the name of each shapefile in the project, along with its filepath and spatial reference. For Part A, we were supposed to isolate the error using a try-except statement instead of fixing it, so that the script could continue to Part B even if Part A didn't work.
I first tried to run the script to see what error I would get. Since there was an issue with the project path, I initially assumed that the script didn’t run because the file path was wrong (I saved the project in my Module3 folder instead of the Data folder within Module3). I tried embedding the 8 lines after the print(“Running Part A…”) message under a try statement and adding a FileNotFoundError under an except statement. When this didn’t fix the problem, I read the error message more carefully and realized that it could probably be fixed by adding aprx as the argument in the line project = arcpy.mp.ArcGISProject(). However, I resisted my impulse to fix it and instead changed the error type in the except statement to a TypeError. Then, the error message from my except statement printed, but I still got another error (NameError: name ‘project’ is not defined), so I realized I had to embed the entire rest of part A (aside from catching the error in the except statement) under the try statement so none of it would run if the conditions weren’t met.
A flowchart of the try-except statement I wrote for Script 3 Part A

Comments
Post a Comment