Click here to view code image
else:
print ()
print ("Data entered successfully")
The optional finally statement is located at the very end of a try except statement block. It
also must follow any included else statement blocks. The Python statements within the finally
statement block are executed whether an exception was raised or not. The following is an example of
a finally statement block:
Click here to view code image
finally:
print ()
print ("Script completed.")
The as variable statement is not a statement block like the others. Instead, it allows you to capture the
exact error message that is issued, when the exception is raised. The beauty here is that no matter
which exception is raised, you have the error message. Often script writers write the message to a log
file for later review and display a very user-friendly style message to the script user instead. The
following is an example of using an as variable statement:
Click here to view code image
except ValueError as input_error:
print ("Numbers entered must be digits.")
print ("Script terminating....")
print ()
error_log_file = open ('/home/pi/data/error.log', 'a')
error_log_file.write(input_error)
error_log_file.close()
exit ()
The variable name here is input_error. If a ValueError exception is raised in this try
except statement block, the exact error message is loaded into the input_error variable. A
Python statement within the block, error_log_file.write(input_error), then writes that
error message out to an error log file.
These three options give a great deal of flexibility in handling exceptions. Now it is time to stop
reading about handling exceptions and try to handle a few yourself.
Try It Yourself: Explore Python try except Statement Blocks
In the following steps, you will explore Python try except statement blocks by
creating a script that opens a file. At first, the script will produce a traceback message.
You will add try except statements to handle the raised exceptions using good
form. Here’s what you do:
- If you have not already done so, power up your Raspberry Pi and log in to the
system. - If you do not have the LXDE GUI started automatically at boot, start it now by typing
startx and pressing Enter. - Open a script editor, either nano or the IDLE 3 text editor, to create the script
py3prog/script1704.py.