about try statement

Bengt Richter bokr at oz.net
Sat Nov 12 06:31:41 EST 2005


On Sat, 12 Nov 2005 10:20:08 +0100, Sybren Stuvel <sybrenUSE at YOURthirdtower.com.imagination> 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



More information about the Python-list mailing list