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?
finally is usually used to close a code properly after its encountered an Exception or Error. This means that no matter whether an exception/error comes or not, 1nce the try/try-catch block ends, the finally block WILL be executed.
The finally keyword is used to execute code (used with exceptions - try.. catch statements) no matter if there is an exception or not.
It makes a difference if you return early:
try: run_code1() except TypeError: run_code2() return None # The finally block is run before the method returns finally: other_code()
Compare to this:
try: run_code1() except TypeError: run_code2() return None other_code() # This doesn't get run if there's an exception.
Other situations that can cause differences:
run_code1()
but it's not a TypeError
.continue
and break
statements.You can use finally
to make sure files or resources are closed or released regardless of whether an exception occurs, even if you don't catch the exception. (Or if you don't catch that specific exception.)
myfile = open("test.txt", "w") try: myfile.write("the Answer is: ") myfile.write(42) # raises TypeError, which will be propagated to caller finally: myfile.close() # will be executed before TypeError is propagated
In this example you'd be better off using the with
statement, but this kind of structure can be used for other kinds of resources.
A few years later, I wrote a blog post about an abuse of finally
that readers may find amusing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With