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

(singke) #1
pi@raspberrypi ~ $ cat py3prog/my_errors.py
1: # my_errors.py - Demonstrates various Python errors
2: # Written by Blum and Bresnahan
3: #
4: #####################################################
5: #
6: ############# Initialize Variables ##################
7: #
8: my_error = 0
9: num_1 = 3
10: num_2 = 4
11: zero = 0
12: #
13: ############# Error Functions ########################
14: #
15: #def missing_quote ():
16: # print ()
17: # print ("I love my Raspberry Pi!)
18: #
19: def divide_zero ():
20: print ()
21: print ("The Classic \"Divide by Zero\" error.")
22: print ()
23: my_error = num_1 / zero
24: #
25: ############## Mainline ##############################
...
pi@raspberrypi ~ $

Understanding error exceptions is important for handling them within a Python script. Now that you
have an understanding of exceptions, the next step is to learn how to properly handle them.


Handling Exceptions


As you have seen, when runtime errors are encountered in a script, the script stops, throws an
exception, and produces a traceback message. This is pretty sloppy and could certainly terrify an
unsuspecting script user. However, you can handle runtime errors with good form and keep your
script users happy. Python provides an exception handler via the try except statement.


The basic syntax of a try except statement is as follows:


Click here to view code image


try:
python statements
except exception_name:
python statements to handle exception

Notice that indentation is used with the try except statement to indicate which Python statements
belong together. The Python statements within the try statement area are part of the try statement
block. Python statements within the except statement area are part of the except statement block.
Together, the two blocks are called the try except statement block.


Using the example of the divide–by-zero exception, Listing 17.7 shows a script that could raise this
exception, along with a try except statement to properly handle it. The try except statement
block starts on line 15 and ends on line 22. Any Python statement that may raise an exception should
be put in a try statement block (Listing 17.7 lines 15 through 17) in order to properly handle that

Free download pdf