Chapter 7: Exception handling

After handling the exceptions

face Josiah Wang

Sometimes we need to continue running some code, but only if no error occurred. For example, lines 3-5 run if there are no errors. And whether or not there was a ZeroDivisionError, we will print "The end." (line 9).

1
2
3
4
5
6
7
8
9
try:
    x = a / b 
    y = x * 5
    z = y + 1
    print(x + y + z)
except ZeroDivisionError: 
    print("b should not be zero.")

print("The end.")

But I also mentioned earlier that PEP 8 actually recommends that you keep the code in a try clause to the absolute minimum necessary. This avoids disguising a different error (perhaps a ZeroByDivisionError might occur in a different line).

So how do we keep the try block minimum, but at the same time execute some code only if there are no errors?

Easy! Use an else clause. Anything inside else will execute only if there were no errors while in the try block.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
try:
    x = a / b 
except ZeroDivisionError: 
    print("b should not be zero.")
else:
    print("No errors. Woohoo!")
    y = x * 5
    z = y + 1
    print(x + y + z)

print("The end.")

Finally, you can also have code that must execute whether or not an exception occurred. Such codes can be put inside a finally block.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
try:
    x = a / b 
except ZeroDivisionError: 
    print("b should not be zero.")
else:
    print("No errors. Woohoo!")
    y = x * 5
    z = y + 1
    print(x + y + z)
finally:
    print("The end.")

How is it different from not using finally? Well, the finally block must run, whatever happens. For example, line 2 in the example below should raise a ValueError but is not caught. If you run this code, Python will naturally report a ValueError, but notice what gets printed before that? You guessed it - "The end.".

1
2
3
4
5
6
try: 
    y = int("a string")
except ZeroDivisionError: 
    print("b should not be zero.")
finally:
    print("The end.")

The finally clause is mainly useful for specifying some ‘cleanup’ code. For example, we might need to close a file properly, whether or not any error occurs while the file is still open.