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

(singke) #1
Please enter number to divide: 3

Please enter the divisor: ^C
Script terminating....
pi@raspberrypi ~ $

The final three tests on script1704.py in Listing 17.13 test the newly separated try except
statement blocks of the script. Notice that the last test uses Ctrl+C. The keyboard interrupt exception
is handled gracefully. If this exception were not trapped, it would produce a very long and ugly
traceback message.


Handling Generic Exceptions


So far, you have seen anticipated exceptions being handled. However, few people can determine all
the possible error exceptions that may be raised. Fortunately, Python allows a generic exception for
unanticipated events.


The syntax for generic exceptions is not too different from that of regular exceptions. You simply
leave off the exception name from the except statement, as shown in Listing 17.14.


LISTING 17.14 A Generic Execution Statement


Click here to view code image


pi@raspberrypi ~ $ cat py3prog/script1703.py
...
except:
print ()
print ("An error has occurred.")
print ("Script terminating...")
print ()
exit ()
...

In Listing 17.14, the script1703.py has its first try except statement block modified to
include a generic exception statement. Notice that the only syntax difference between the generic
exception statement and the others is that no exception name is listed after except. Now if any
unforeseen exceptions are raised, the script can handle them in good form.


Understanding try except Statement Options


Several optional items you can use within your try except statement blocks provide a great deal
of flexibility. These are the three primary options:


else statement block
finally statement block
as variable statement

An optional else statement block follows an except statement block and also contains Python
statements. However, these Python statements are executed only if no exceptions were raised by
Python statements within a try statement block. The following is an example of an else statement
block:

Free download pdf