Page 14 -
P. 14
table of contents
files and exceptions
3 Dealing with errors
It’s simply not enough to process your list data in your code.
You need to be able to get your data into your programs with ease, too. It’s no surprise
then that Python makes reading data from files easy. Which is great, until you
consider what can go wrong when interacting with data external to your programs…
and there are lots of things waiting to trip you up! When bad stuff happens, you need a
strategy for getting out of trouble, and one such strategy is to deal with any exceptional
situations using Python’s exception handling mechanism showcased in this chapter.
Data is external to your program 74
It’s all lines of text 75
Take a closer look at the data 77
Know your data 79
Know your methods and ask for help 80
Know your data (better) 82
Two very different approaches 83
Add extra logic 84
Handle exceptions 88
Try first, then recover 89
Identify the code to protect 91
Take a pass on the error 93
What about other errors? 96
Add more error-checking code… 97
…Or add another level of exception handling 98
So, which approach is best? 99
You’re done…except for one small thing 101
Be specific with your exceptions 102
split(beans)
Your Python Toolbox 103
xii