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

This post is about the Python keyword except, not to mention try and finally.

except

This Python keyword except 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`