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

(singke) #1
the as variable statement into the variable open_error, an exception must be
named. Using the overall base group Exception means that all exceptions will be
caught. Save the editor contents to a file and exit the editor.


  1. 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. As shown below, your new except statement block should catch the
    raised exception and display the information desired:


Click here to view code image


pi@raspberrypi ~ $ python3 py3prog/script1704.py

Please enter file to open: nofile

An error exception has been raised.
The error message is:
[Errno 2] No such file or directory: 'nofile'
pi@raspberrypi ~ $


  1. To clean up script1704.py a little more (and give you more experience!), open
    the script in your favorite script editor again. 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')
print ("File", file_name, "opened successfully!")
my_file.close()
#
except IOError:
print ("File", file_name, "not found")
print ("Script terminating...")
return
#
except Exception as open_error:
print ("An error exception has been raised.")
print ("The error message is:")
print (open_error)
print ()
return
#


  1. Notice that the change you made was to add an additional except statement block
    to the function. The additional statement specifically catches any IOError
    exceptions. Save the editor contents to a file and exit the editor.

  2. 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. The except statement block should catch the raised exception and
    display the information desired, as shown below:


Click here to view code image


pi@raspberrypi ~ $ python3 py3prog/script1704.py
Free download pdf