Page 137 -
P. 137
files and exceptions
You’re done…except for one small thing
Your exception-handling code is good. In fact, your code might be too good in
that it is too general.
At the moment, no matter what error occurs at runtime, it is handled by your
code because it’s ignored or a error message is displayed. But you really need to
worry only about IOErrors and ValueErrors, because those are the types
of exceptions that occurred earlier when your were developing your program.
Although it is great to be able to handle all runtime errors, it’s probably
unwise to be too generic…you will want to know if something other than
an IOError or ValueError occurs as a result of your code executing at
runtime. If something else does happen, your code might be handling it in an
inappropriate way.
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:
This code and this code runs when ANY
pass
runtime error occurs within the code that
data.close() is being tried.
except:
print('The data file is missing!')
As your code is currently written, it is too generic. Any runtime error that
occurs is handled by one of the except suites. This is unlikely to be what
you want, because this code has the potential to silently ignore runtime errors.
You need to somehow use except in a less generic way.
you are here 4 101