1

On this link (https://docs.python.org/2/tutorial/errors.html#defining-clean-up-actions) following is said:

A finally clause is always executed before leaving the try statement, whether an exception has occurred or not.

CODE 1:

try:
    print "Performing an action which may throw an exception."
except Exception, error:
    print "An exception was thrown!"
    print str(error)
else:
    print "Everything looks great!"
finally:
    print "Finally is called directly after executing the try statement whether an exception is thrown or not."

OUTPUT 1:

Performing an action which may throw an exception.
Everything looks great!
Finally is called directly after executing the try statement whether an exception is thrown or not.

CODE 2:

try:
    print "Performing an action which may throw an exception."
    raise  Exception('spam', 'eggs') # This is new
except Exception, error:
    print "An exception was thrown!"
    print str(error)
else:
    print "Everything looks great!"
finally:
    print "Finally is called directly after executing the try statement whether an exception is thrown or not."

OUTPUT 2:

Performing an action which may throw an exception.
An exception was thrown!
('spam', 'eggs')
Finally is called directly after executing the try statement whether an exception is thrown or not.

What I get from this is that else is executed only when there is no exception.

QUESTION:
Is finally used just for better readability ?
Because I can just put this print statement after try, like in this code.

CODE 3:

try:
    print "Performing an action which may throw an exception."
    #raise  Exception('spam', 'eggs') # with this line or without last print is done
except Exception, error:
    print "An exception was thrown!"
    print str(error)
else:
    print "Everything looks great!"

print "Finally is called directly after executing the try statement whether an exception is thrown or not."
WebOrCode
  • 6,852
  • 9
  • 43
  • 70
  • 1
    The print statement would not be executed if any of the code *returned* if in a funcction, or used `continue` or `break` if in a loop. – Martijn Pieters Oct 09 '14 at 16:08
  • Isn't the finally statement there for clean-up purposes? Moreover, [isn't it the same in java?](http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html]) – JoErNanO Oct 09 '14 at 16:09
  • Does this answer your question? [Why do we need the "finally" clause in Python?](/q/11551996/90527) – outis Oct 17 '22 at 02:49

2 Answers2

6

There are circumstances where the finally suite is always executed, but your print statement would not:

  1. When there is an unhandled exception in your try.
  2. When your try is in a loop (while or for) and you used a break or continue statement
  3. When your try is in function and you used a return statement.

The finally suite then is used to guarantee that code is executed, regardless of what happens in the try block, even when exited before reaching the end of the block.

Compare:

def foo():
    try:
        print "Performing an action which may throw an exception."
        return
    except Exception as error:
        print "An exception occured!", error
    finally:
        print "Cleaning up"

with

def bar():
    try:
        print "Performing an action which may throw an exception."
        return
    except Exception as error:
        print "An exception occured!", error
    print "Cleaning up"

In bar() the last message is not printed:

>>> foo()
Performing an action which may throw an exception.
Cleaning up
>>> bar()
Performing an action which may throw an exception.
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Is `sys.exit` a fourth? (or is that covered by unhandled exception?) – GP89 Oct 09 '14 at 16:13
  • @GP89: `sys.exit()` throws an exception, so that falls under the unhandled exception case. – Martijn Pieters Oct 09 '14 at 16:14
  • can you provide some code example where my print statement from `CODE 3`, would not be executed, that I thing I will get it. Thanks – WebOrCode Oct 09 '14 at 16:15
  • @WebOrCode: added an example. – Martijn Pieters Oct 09 '14 at 16:18
  • @MartijnPieters Ah but this goes against the single return point paradigm! :P – JoErNanO Oct 09 '14 at 16:19
  • @MartijnPieters I get it with `return` statement. But I still can not think of real world example of it. Why to put `return` in `try` ? – WebOrCode Oct 09 '14 at 16:27
  • @WebOrCode: Before we had context managers, it was the correct way to ensure that a file is closed whatever happens in the function. `f = open(...)` then put everything in a `try` with `finally: f.close()` at the end. – Martijn Pieters Oct 09 '14 at 16:28
  • 1
    @WebOrCode: the alternative is to always catch *all* exceptions then re-raise after closing the file, *and* closing the file when the code ran successfully. That's not efficient and you end up repeating yourself. – Martijn Pieters Oct 09 '14 at 16:30
1

The finally code block is always executed, whether or not an exception is thrown. This is true in most (I wanted to say all but ...) other languages: C#, Java, etc.

Its function is to allow the execution of clean-up code -- close opened resources, de-allocate memory, etc. -- for the program to continue/terminate its execution in a clean and safe way.

Community
  • 1
  • 1
JoErNanO
  • 2,458
  • 1
  • 25
  • 27