[Tutor] finally

Hugo Arts hugo.yoshi at gmail.com
Thu Jun 24 15:06:24 CEST 2010


On Thu, Jun 24, 2010 at 4:36 AM, Christopher King <g.nius.ck at gmail.com> wrote:
>     In a try except clause, you can end with finally block. I know it runs
> after the try and except blocks regardless of the outcome, but why use it.
> Couldn't you just put the code after the try and except block without using
> a finally block. Does the finally command do something I don't know about.
> Does it make your program more understandable in some way?

The thing about the finally block is that it *always* runs. If you
just put some code after the try: except: clause, it won't run if

a) the exception is not handled in the try: except: block, but higher
up in the call stack
b) the exception is not handled at all
c) the exception handler terminates the program
d) the exception handler raises another exception

If you need to do some cleanup, putting it in a finally block is the
only way to *guarantee* it will run.

Hugo


More information about the Tutor mailing list