Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1
Please enter file to open: nofile

File nofile not found
Script terminating...
pi@raspberrypi ~ $


  1. Open the script1704.py script in a script editor again. This time you will be
    adding the optional else and finally statements. Modify the open_it function
    so that it looks as shown below:
    Click here to view code image
    def open_it (file_name): #Open file name
    try:
    my_file=open(file_name,'r')


    except IOError:
    print ("File", file_name, "not found")
    print ("Script terminating...")



    except Exception as open_error:
    print ("An error exception has been raised.")
    print ("The error message is:")
    print (open_error)
    print ()



    else:
    print ("File", file_name, "opened successfully!")
    my_file.close()



    finally:
    return




  2. Remember that the else statement block is executed only if no exceptions are
    raised. The finally statement block is run whether an exception is raised or not.
    Save the editor contents to a file and exit the editor.

  3. Now test your modified script by typing python3 py3prog/script1704.py
    and pressing Enter. At the Please enter file to open: prompt, type
    nofile and press Enter. You should see a message similar to what is shown
    below:
    Click here to view code image
    pi@raspberrypi ~ $ python3 py3prog/script1704py


Please enter file to open: nofile

File nofile not found
Script terminating...
pi@raspberrypi ~ $

Good job! Hopefully you can see the benefits of properly and gracefully handling exceptions.


If you want a little more hands-on experience, go back through the previous hours and look at

Free download pdf