Click here to view code image
1: pi@raspberrypi ~ $ cat py3prog/script1702.py
2: # script1702 - Properly handle Division Errors
3: # Written by Blum and Bresnahan
4: #
5: #####################################################
6: #
7: ################## Functions ########################
8: #
9: def divide_it ():
10: print ()
11: #
12: try:
13: # Get numbers to divide
14: number=int(input("Please enter number to divide: "))
15: print ()
16: divisor=int(input("Please enter the divisor: "))
17: print ()
18: #
19: # Divide the numbers
20: result = number / divisor
21: print ("The result is:", result)
22:#
23: except ZeroDivisionError:
24: print ("You cannot divide a number by zero.")
25: print ("Script terminating....")
26: print ()
27:#
28: except ValueError:
29: print ("Numbers entered must be digits.")
30: print ("Script terminating....")
31: print ()
32:#
33:############## Mainline #############################
34:#
35:def main ():
36: divide_it ()
37:#
38:############ Call the Main Function ###################
39:#
40: main()
41: pi@raspberrypi ~ $
In Listing 17.10, notice that the input statements were moved from outside the try except
statement block to inside it on lines 14 and 16. This is done because the ValueError exception can
occur when the user is entering input to these statements. The Python statements that can throw an
exception must be within the try statement block in order for the exceptions to be handled by the
try except block. Now both ValueError and ZeroDivisionError exceptions raised by
Python statements within the try statement block can be properly handled.
Listing 17.11 shows a user attempting input three different times on script1702.py.
LISTING 17.11 Execution of script1702.py
Click here to view code image