Chapter Eight · Failing Well
When Things Go Wrong
Every program meets bad input, missing files and its own mistakes. This chapter turns errors from crashes into messages a program can answer: what an exception is, how to catch exactly the ones you expect, how to raise your own, how to handle a bad row of data without crashing or hiding it, and how to find a bug with a method instead of luck.
You have been reading error messages since Chapter 1. Every one of them, from the NameError at the prompt to the FileNotFoundError in Chapter 7, was an exception: Python's way of saying "I cannot continue with this, and here is exactly why". This chapter is about what a program can do in reply.
Five topics. What an exception is, and how to read one that passed through several functions. try and except, used precisely, so that expected problems get handled and real bugs still show. raise, so your own functions can refuse bad input with a clear message. A realistic case: one malformed row in a bank statement, handled so the report is both produced and honest. And debugging, the method for the bug that raises no exception at all and just gives the wrong answer.
Topics in This Chapter
raise, writing a message a person can act on, and checking data where it enters the program.breakpoint(), and change one thing at a time.