Chapter 7: Exception handling

Exercise (opening a file)

face Josiah Wang

Let’s do one more exercise!

Here is another short piece of code. I will assume there is NO file called "nosuchfile.txt" in the same directory as the script, so an exception will occur because of that. You can run this script to figure out what kind of error will be raised.

Again, modify this code so that it displays a user-friendly error message, rather than Python’s ugly one (at least, ugly to someone who does not understand programming!) Along with your user-friendly message, you must also make sure that the message in Line 5 gets displayed whether or not an error occurs!

1
2
3
4
5
with open("nosuchfile.txt") as textfile:
    for line in textfile:
        print(line)

print("I have an important message!")