Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need the "finally" clause in Python?

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?

like image 430
RNA Avatar asked Jul 18 '12 23:07

RNA


People also ask

What is the purpose of the finally clause?

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.

What is the purpose of finally class?

The finally keyword is used to execute code (used with exceptions - try.. catch statements) no matter if there is an exception or not.


2 Answers

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:

  • If an exception is thrown inside the except block.
  • If an exception is thrown in run_code1() but it's not a TypeError.
  • Other control flow statements such as continue and break statements.
like image 74
Mark Byers Avatar answered Sep 21 '22 16:09

Mark Byers


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.

like image 34
kindall Avatar answered Sep 22 '22 16:09

kindall