The ABCs of Python: “except,” “try,” “finally,” and Looney Tunes

Here are three more keywords in Python:

except

This keyword is used to code for what Python calls (what else?) “exceptions,” which tend to mean that something has gone wrong in the execution of a program. That is, the program works except in a certain circumstance, as in, “Nothing can harm Superman except Kryptonite.” This keyword is partnered up with another one: try. That’s why I’m placing try below, along with some code that uses them in tandem.

try 

This is try as in “try this and see what happens.” Below is a function in which we use try and except. All we’re doing is employing the index function to select a specific number from an array of numbers in a list. For example, let’s say we pick the third number in this list — [20, 12, 99, 15, 78] – remembering that we start counting from zero in Python. The third number here is 15. We then multiply 15 by itself three times. We’re going to call this function in several different ways so you can see how the code works.

def power_up_index(array, n):
     '''
     Find Nth power of the element with index N.
     '''
     try:
         return array[n]**n
     except IndexError:
         return ("Not gonna work")
print(power_up_index ([20, 12, 99, 15, 78], 3))
'''
the number 3 is n in this case. You pick the third
number and multiply that number by itself three times.
'''
print(power_up_index([1, 2, 3, 4], 2)) #you multiply 3 
                                       #by itself two times
print(power_up_index([1, 2], 3))
'''
you get an error message because the computer cannot locate the 
third number in this array (which only has two numbers,
as you can see). Thus, you get the “Not gonna work” message.
'''

This code will produce three lines:

3375
9
Not gonna work

finally

By using finally, you can always get the final word in. Even if your error code appears as a result of an exception, you can still say or do something else. The following code is another version of what we just saw, except this time we get in the sign-off of “That’s all, folks!” regardless of what else happens.

You can, of course, do other things with finally as well. For example, if your code opens a file but something goes wrong in the execution of your program, you can still close your file with the finally statement. This ensures you can tidy things up.

def power_up_index(array, n):
     '''
     Find Nth power of the element with index N.
     '''
     try:
         print ("The answer is: " + str(array[n]**n))
     except IndexError:
         print ("Not gonna work")
     finally:
         print ("That's all, folks!")
(power_up_index ([20, 12, 99, 15, 78], 3))
(power_up_index([1, 2], 3))

This time around, we get the following results:

The answer is: 3375
That’s all, folks!
Not gonna work
That’s all, folks!

PS – For more on information on exception handling, I recommend tutorialspoint.

Featured image from Intertitle of the Public Domain short film "Crowing Pains," 1947, Warner Brothers

Published by

Mark R. Vickers

I am a writer, analyst, futurist and researcher. I've spent most of my working life as an editor and manager for research organizations focusing on social, business, technology, HR and management trends. But, perhaps more to the point for this blog, I'm curious about the universe and the myriad, often mysterious relationships therein.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s