Page 151 -
P. 151
persistence
Extend try with finally
When you have a situation where code must always run no matter what errors
occur, add that code to your try statement’s finally suite:
try:
man_file = open('man_data.txt', 'w')
No changes other_file = open('other_data.txt', 'w')
here, except
that… print(man, file=man_file)
print(other, file=other_file)
except IOError:
print('File error.')
…the calls to finally:
“close()” are
moved to here. man_file.close()
other_file.close()
If no runtime errors occur, any code in the finally suite executes. Equally,
if an IOError occurs, the except suite executes and then the finally
suite runs.
No matter what, the code in the finally suite always runs.
By moving your file closing code into your finally suite, you are reducing
the possibility of data corruption errors.
This is a big improvement, because you’re now ensuring that files are closed
properly (even when write errors occur).
But what about those errors?
How do you find out the specifics of the error?
you are here 4 115