Errors and Debugging
Programs meet bad input, missing files and their own bugs. You'll catch exceptions with try and except, raise your own when a value makes no sense, and choose between raising an error and returning a value. Then you'll pause a program in VS Code's debugger and step through it line by line, and build a parking garage kiosk that never crashes on a typo.
Updated
Exceptions in Python
- Handling Errors with try and except (Apprentice): An exception is Python's report of an error while a program runs, and try and except let a program catch the one it expects, such as the ValueError from turning "two" into a number, with else for what runs when nothing went wrong and finally for what runs every time.
- Raising Your Own Exceptions (Journeyman): A function that's handed a value that makes no sense should refuse it with raise and a message that says what was wrong, can name its own kind of error with a small exception class, and raises rather than returning None when carrying on would give a wrong answer.
Debugging Python
- Finding Bugs with the Debugger (Apprentice): When a program gives a wrong answer with no error to read, VS Code's debugger pauses it at a breakpoint and runs it one line at a time with Step Over and Step Into, while the Variables panel and Watch show every value change, until the line that goes wrong shows itself.
Exercise: Parking Kiosk
- Exercise: Parking Kiosk (Journeyman): Write the three functions behind a parking garage's pay kiosk, which turn what drivers type into hours or refuse it with a clear ValueError, price the stay or refuse impossible hours with a KioskError, and keep asking until an answer can be priced, and let pytest check what each one returns, raises and prints.