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

(singke) #1
4:
5: Please enter the divisor: 4
6:
7: The result is: 0.75
8: pi@raspberrypi ~ $
9: pi@raspberrypi ~ $ python3 py3prog/script1701.py
10:
11: Please enter number to divide: 3
12:
13: Please enter the divisor: 0
14:
15: You cannot divide a number by zero.
16: Script terminating....
17:
18: pi@raspberrypi ~ $

On the second run of the script in Listing 17.8, the user puts 0 as the divisor on line 13. This raises an
exception. However, the script is not abruptly halted, nor is a scary traceback message displayed.
Instead, because the exception occurs within the try except statement block, the exception is
“caught,” and the Python statements within the except statement block run, as shown on lines 15 and



  1. This is considered good form for handling raised exceptions within scripts.


Handling Multiple Exceptions


Often you need to be able to “catch” more than one type of exception for a group of Python statements.
For example, using the script1701.py script, if the user enters a word instead of a number,
Listing 17.9 shows what happens.


LISTING 17.9 Additional Exceptions Not Handled


Click here to view code image


pi@raspberrypi ~ $ python3 py3prog/script1701.py

Please enter number to divide: 3

Please enter the divisor: four
Traceback (most recent call last):
File "py3prog/script1701.py", line 30, in <module>
main()
File "py3prog/script1701.py", line 26, in main
divide_it ()
File "py3prog/script1701.py", line 12, in divide_it
divisor=int(input("Please enter the divisor: "))
ValueError: invalid literal for int() with base 10: 'four'

Even though the script can handle a ZeroDivisionError exception, it has not been written to
handle a ValueError exception. Multiple exceptions can be handled within a try except
statement block for cases such as this. script1701.py was modified to include such a block and
was renamed script1702.py. The new script is shown in Listing 17.10.


LISTING 17.10 Handling Multiple Exceptions

Free download pdf