I am not sure why we need finally
in try...except...finally
statements. In my opinion, this code block
try:
run_code1()
except TypeError:
run_code2()
other_code()
is the same with this one using finally
:
try:
run_code1()
except TypeError:
run_code2()
finally:
other_code()
Am I missing something?
They are not equivalent. Finally code is run no matter what else happens. It is useful for cleanup code that has to run.
As explained in the documentation, the
finally
clause is intended to define clean-up actions that must be executed under all circumstances.An example:
As you can see, the
finally
clause is executed in any event. TheTypeError
raised by dividing two strings is not handled by theexcept
clause and therefore re-raised after thefinally
clause has been executed.In real world applications, the finally clause is useful for releasing external resources (such as files or network connections), regardless of whether the use of the resource was successful.
In your first example, what happens if
run_code1()
raises an exception that is notTypeError
? ...other_code()
will not be executed.Compare that with the
finally:
version:other_code()
is guaranteed to be executed regardless of any exception being raised.It makes a difference if you return early:
Compare to this:
Other situations that can cause differences:
run_code1()
but it's not aTypeError
.continue
andbreak
statements.The code blocks are not equivalent. The
finally
clause will also be run ifrun_code1()
throws an exception other thanTypeError
, or ifrun_code2()
throws an exception, whileother_code()
in the first version wouldn't be run in these cases.A try block has just one mandatory clause: The try statement. The except, else and finally clauses are optional and based on user preference.
finally: Before Python leaves the try statement, it will run the code in the finally block under any conditions, even if it's ending the program. E.g., if Python ran into an error while running code in the except or else block, the finally block will still be executed before stopping the program.