- finally
Exceptions finally
- We can add a "finally" section to the end of the "try" - "except" construct.
- The code in this block will be executed after every time we enter the try.
- When we finish it successfully. When we catch an exception. (In this case a ZeroDivisionError exception in file zero.txt)
- Even when we don't catch an exception. Before the exception propagates up in the call stack, we still see the "finally" section executed.
examples/exceptions/finally.py
import sys import module # python finally.py one.txt zero.txt two.txt three.txt files = sys.argv[1:] for filename in files: try: module.read_and_divide(filename) except ZeroDivisionError as err: print("Exception {} of type {} in file {}".format(err, type(err).__name__, filename)) finally: print("In finally after trying file {}".format(filename)) print('')
before one.txt 100.0 after one.txt In finally after trying file one.txt before zero.txt Exception division by zero of type ZeroDivisionError in file zero.txt In finally after trying file zero.txt before two.txt In finally after trying file two.txt Traceback (most recent call last): File "finally.py", line 9, in <module> module.read_and_divide(filename) File "/home/gabor/work/slides/python-programming/examples/exceptions/module.py", line 3, in read_and_divide with open(filename, 'r') as fh: FileNotFoundError: [Errno 2] No such file or directory: 'two.txt'