Ben Chuanlong Du's Blog

It is never too late to learn.

The try/except/finally Block in Python

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

Tips and Traps

  1. The finally statements are guaranteed to be executed (presuming no power outage or anything outside of Python's control) after a try/except block runs even if return, break or continue is used in a try/except block. This mean that a if a finally block presents the function won't exit immediate on reaching a return statement in a try/except block. Instead, the function will wait until the finally block is executed to exit. If another return statement is run in the finally block, the previous return value is overwritten. This means that you should never use a return/yield statement in a finally block.
In [7]:
def f1():
    try:
        print("Beginning of the try block (before return) ...")
        return 1
        print("End of the try block (after return) ...")
    except:
        return 2
    else:
        return 3
    finally:
        print("Beginning of the finally block (before return) ...")
        return -1
        print("end of the finally block (after return) ...")


f1()
Beginning of the try block (before return) ...
Beginning of the finally block (before return) ...
Out[7]:
-1
In [8]:
def f2():
    try:
        raise RuntimeError
    except:
        print("Beginning of the exception block (before return) ...")
        return 1
        print("End of the exception block (after return) ...")
    else:
        return 2
    finally:
        print("Beginning of the finally block (before return) ...")
        return -1
        print("end of the finally block (after return) ...")


f2()
Beginning of the exception block (before return) ...
Beginning of the finally block (before return) ...
Out[8]:
-1
In [10]:
def f3():
    try:
        raise RuntimeError
    except:
        print("Beginning of the exception block (before return) ...")
        return 1
        print("End of the exception block (after return) ...")
    else:
        return 2
    finally:
        print("The finally block is run.")


f3()
Beginning of the exception block (before return) ...
The finally block is run.
Out[10]:
1
In [ ]:

Comments