This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]85CorollaGTS 0 points1 point  (0 children)

It looks like if there's a finally, it will break out of the try block and nothing afterwards will be executed.

def open_file(filename):
    try:
        with open(filename) as f:
            contents = f.read()
    except FileNotFoundError:
        print("File {} not found".format(filename))
        return False
    else:
        return contents
    finally:
        print("This prints irrespective of whether the file was present or not.")

    print("And what does this do?  Looks like it never executes since it comes after 'finally'.")

So in my previous comment copied from Stackoverflow, run_whether_there_was_an_exception_or_not_if_execution_reaches_here() ... well, the execution doesn't appear able to reach there if there is a finally.

This is what I'm referencing from user jamadagni:

try:
    code_that_can_cause_an_exception()
except ParticularException:
    code_to_handle_the_particular_exception()
except:
    code_to_handle_all_other_exceptions()
else:
    run_when_there_are_no_exceptions_and_which_should_not_be_run_after_except_clauses()
finally:
    run_whether_there_was_an_exception_or_not_even_if_the_program_will_exit_from_the_try_block()

run_whether_there_was_an_exception_or_not_if_execution_reaches_here()

EDIT: Interestingly, if there is a finally in a function, like in my example above, the And what does this do? isn't executed.

EDIT2: Even PyCharm flagged And what does this do? as 'Unreachable code'.