However, when an exception is raised, Python looks at the except statements within
the try except statement block in the order in which they are listed in the block. If
you have named except statement blocks for both ArithmeticError and
ZeroDivisonError, and a ZeroDivisionError is raised, the block that
comes first is executed.
Notice that exit function statements are added in lines 23, 29, and 40 of the script in Listing 17.12.
These statements are needed because the script does not stop executing when a raised exception is
caught by a try except statement block. Specifically, lines 23 and 29 need exit statements
because if the data input is interrupted by a Ctrl+C, the raised exception is caught, but all the data
needed by the division statement on line 33 will not have been entered.
By the Way: Any Python Statements
You can put just about anything within exception statement blocks. For example,
instead of issuing an exit statement as shown in the preceding examples, you could
issue a return statement to leave the current function but not exit the Python script.
In Listing 17.13, four tests are conducted on script1703.py to see if it can properly handle data
and a few potential exceptions. The first test simply makes sure the script can properly handle good
data.
LISTING 17.13 Execution of script1703.py
Click here to view code image
pi@raspberrypi ~ $ python3 py3prog/script1703.py
Please enter number to divide: 3
Please enter the divisor: 4
The result is: 0.75
pi@raspberrypi ~ $ python3 py3prog/script1703.py
Please enter number to divide: 3
Please enter the divisor: four
Numbers entered must be digits.
Script terminating....
pi@raspberrypi ~ $ python3 py3prog/script1703.py
Please enter number to divide: 3
Please enter the divisor: 0
You cannot divide a number by zero.
Script terminating....
pi@raspberrypi ~ $ python3 py3prog/script1703.py