Chapter 7 reviews the types of errors you can come across while scripting and the most common procedures used to solve them.
Python IDEs have built-in error checking processes that will alert you of any known errors in the script. If you read the error carefully, you may be able to fix the error yourself, without seeking further help. You should keep indentation and spacing consistent in your scripts or you may produce an error. Syntax errors may be caught as they appear in Spyder and PyCharm. Spyder will display a small red x which opens a pop-up window for syntax errors that appear as you type. Spyder can catch other types of errors such as inconsistent indentation. In PyCharm you can produce a general report to see what types of errors are in your script by clicking Code (at the top of the menu) > Inspect code and then selecting the current script.
There are multiple ways to debug your code. The main ways include carefully reading error messages, adding print messages to your script, selectively commenting out code, or using a python debugger. Debugging will not tell you why a script failed, but it will tell you the line in which it failed. (See pg 224-234 for reference of these techniques.)
You can help handle exceptions by using a “try-except” statement (see pg 237). You can use these to produce text that can help you understand what went wrong. An example for a tuple is seen below:
except (ZeroDivisionError, ValueError):
print (“Your entries were not valid.”)
Using a Python debugger (pg 229):
1. Check for syntax errors then save the script.
2. Set breakpoints, allowing you to pause running the script at specific lines.
3. Run the script with a debugger.
4. Walk through the script while looking out for values of important variables.
Syntax errors – errors involved with spelling, punctuation, indentation, or other conventions of the Python language. If you click Run > Check Module and a syntax error appears, a red bar will appear on the line of which the error resides.
Excepts – Events that have no real error but are a result of the data and the script run. An example of this would be to write a script to produce a count of the feature classes in a feature class list. If there are zero feature classes in the list then the code may run perfectly fine but produce no output. This is not truly an error as the code has run correctly.
commenting out code – Placing a double hashtag (##) before lines of code helps cancel out that line in order to isolate parts of the script. This helps find errors in the script.
breakpoints – The code will run until it reaches a breakpoint. They are good for debugging scripts. To set a breakpoint, right-click a line of code and select Set Breakpoint. This will highlight the line yellow.