Discussion in 'Python' started by Shi Mu, Nov 12, 2005.

1. ### Shi MuGuest

very hard for me to understand the difference between
try...except and try...finally

Shi Mu, Nov 12, 2005

2. ### Sybren StuvelGuest

Shi Mu enlightened us with:
> very hard for me to understand the difference between try...except
> and try...finally

Within a 'try' block, if an exception is called and a matching
'except' block is found, that block will be used to handle the
expression.

From the documentation of the "return" keyword: "When return passes
control out of a try statement with a finally clause, that finally
clause is executed before really leaving the function." Note that
there is no talk about exceptions in this.

Sybren
--
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself?
Frank Zappa

Sybren Stuvel, Nov 12, 2005

3. ### Bengt RichterGuest

On Sat, 12 Nov 2005 10:20:08 +0100, Sybren Stuvel <> wrote:

>Shi Mu enlightened us with:
>> very hard for me to understand the difference between try...except
>> and try...finally

>
>Within a 'try' block, if an exception is called and a matching
>'except' block is found, that block will be used to handle the
>expression.
>
>From the documentation of the "return" keyword: "When return passes
>control out of a try statement with a finally clause, that finally
>clause is executed before really leaving the function." Note that
>there is no talk about exceptions in this.
>

Which is because in the finally block the exception is still "live"
and will take effect as soon as the finally block is left, e.g.,

>>> try:

... try: 1/0
... finally: print 'exception can not bypass finally'
... except Exception, e:
... print '%s: %s' %(e.__class__.__name__, e)
...
exception can not bypass finally
ZeroDivisionError: integer division or modulo by zero

Or to make the point about return
>>> def foo(den):

... try:
... try: return 1/den
... finally: print 'exception can not bypass finally'
... except Exception, e:
... print '%s: %s' %(e.__class__.__name__, e)
... return 'succeeded in returning something'
...
>>> foo(0)

exception can not bypass finally
ZeroDivisionError: integer division or modulo by zero
'succeeded in returning something'
>>> foo(1)

exception can not bypass finally
1

Regards,
Bengt Richter

Bengt Richter, Nov 12, 2005