简体   繁体   中英

Try/Except block in a function returns None on exception: will this still run the Finally block?

I'm currently attempting to write the second part of a quiz program, which uses a simple function load_quiz to load a .json file containing the quiz data, and if a file is not found or is empty it will simply return nothing and refuse playing the quiz.

My code is as follows:

def load_quiz():

    quiz = None
    try:
        with open('quiz.json', 'r') as f:
            quiz = json.load(f)
    except (OSError, ValueError):
        print("Quiz file not found/empty! Please load an unemptied quiz .JSON in order to play.")
        return None
    finally:
        if quiz and quiz[playable]:
            play_quiz(f)
        else:
            print("Quiz file invalid! Please load a valid .JSON in order to play.")
            return None

What I'm wondering is if this approach would even work. If the function returns None within the except block, will that still execute whatever is in the finally block, or will the function simply stop there? If not, then how would I go around that?

Is this a viable option?

If you have this function:

def divide(x, y):
    try:
        return x / y
    except ZeroDivisionError:
        return 0
    finally:
        print('always')

The finally will be executed in the case without an exception:

>>> divide(1, 2)
always
0.5

and in the case the exception got raised and caught:

>>> divide(1, 0)
always
0

As you can see, the always is printed before the return of the function, even though visually the return comes before the finally .

The finally clause is also executed “on the way out” when any other clause of the try statement is left via a break , continue or return statement.

https://docs.python.org/3.5/tutorial/errors.html#defining-clean-up-actions

The finally block still gets executed. In fact, it gets executed before the return statement in the except block is executed. Hence you will get a None value returned from the finally block not from the except block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM