about try statement

S

Shi Mu

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

Sybren Stuvel

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
 
B

Bengt Richter

Shi Mu enlightened us with:

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: 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 ... 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'
... exception can not bypass finally
ZeroDivisionError: integer division or modulo by zero
'succeeded in returning something' exception can not bypass finally
1

Regards,
Bengt Richter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top