In the following example the program will ask the user for the name of a file and then process that file by reading in the data and providing a sum of the numbers in the file. The first row in the file must contain the number of rows to be summed (not including the first row).
Fix the program so that it can catch the following errors and asks the user to re-enter a new filename.
You can test your solution by selecting the files in the tabs provided in the trinket.
User enters a filename that does not exist. Ask the user to type in a new file name that does exist (catch an IOERROR)
The number at the top of the file has the incorrect number of rows (raise and catch a ValueError)
The number at the top of the file is not an integer (raise and catch a ValueError)
One of the numbers to be summed is not an integer (raise and catch a ValueError)
There are more rows in the file than indicated by the number in the first row (raise and catch RuntimeError)
10
1
2
3
4
5
6
7
8
9
10
Occasionally, you need to take some action whether or not an exception is raised. The finally construct is used to handle this situation. Here is a typical situation. It is important to close an output file to ensure that all output is written to the file. In the following code segment, we open an output file, call one or more functions, and then close the file:
Now suppose that one of the methods or functions before the last line raises an exception. Then the call to close is never executed! You solve this problem by placing the call to close inside a finally clause:
In a normal case, there will be no problem. When the try block is completed, the finally clause is executed, and the file is closed. However, if an exception occurs, the finally clause is also executed before the exception is passed to its handler.