Page 138 -
P. 138
specify exceptions
Be specific with your exceptions
If your exception-handling code is designed to deal with a specific type of
error, be sure to specify the error type on the except line. In doing so, you’ll
take your exception handling code from generic to specific.
try:
data = open('sketch.txt')
for each_line in data:
try:
(role, line_spoken) = each_line.split(':', 1)
print(role, end='')
print(' said: ', end='')
print(line_spoken, end='')
except ValueError:
pass
Specify the type of runtime
data.close() error you are handling.
except IOError:
print('The data file is missing!')
Of course, if an different type of runtime error occurs, it is no longer handled
by your code, but at least now you’ll get to hear about it. When you are
specific about the runtime errors your code handles, your programs no longer
silently ignore some runtime errors.
...and it lets you avoid
Using “try/except” adding unnecessary code
lets you concentrate and logic to your programs.
on what your code That works for me!
needs to do...
102 Chapter 3