Does Python do try: except: finally: ?

logistix logistix at zworg.com
Wed Mar 19 21:33:23 EST 2003


"Ulrich Petri" <ulope at gmx.de> wrote in message news:<b5b0de$253ft3$1 at ID-67890.news.dfncis.de>...
> "Skip Montanaro" <skip at pobox.com> schrieb im Newsbeitrag
> news:mailman.1048112434.6123.python-list at python.org...
> >
> > Maybe, but that's not what try/finally does.  Try/finally says, "Execute
>  the
> > code in the try block, and irregardless of any exceptions which might get
> > raised, execute the code in the finally block when finished."
> > Try/except/else says, "Execute the code in the try block.  If an exception
> > is raised, execute the code in the except block, otherwise execute the
>  code
> > in the else block."
> >
> 
> I allways asked myself of what practical use finally (except the syntactical
> "clearness of code") is?
> I can simply write like:
> 
> try:
>     do_this()
> except:
>     print "error"
> #now here is what will be executed next, so what for i do need finally?
> 
> Ciao Ulrich

It gets really ugly if you're trying to defer the error handling:

>>> def fileOp():
...     try:
...         print "Pretend to open a file"
...         print "Pretend to process"
...         raise RuntimeError("Pretend I had an error")
...     finally:
...         print "Pretend to close a file"
... 		
>>> fileOp()
Pretend to open a file
Pretend to process
Pretend to close a file
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
  File "<interactive input>", line 5, in fileOp
RuntimeError: Pretend I had an error
>>> try:
...     fileOp()
... except:
...     print "Ignoring Error"
... 	
Pretend to open a file
Pretend to process
Pretend to close a file
Ignoring Error
>>> 
>>> 
>>> def fileOp():
...     errStatus = 0
...     try:
...         print "Pretending to open a file"
...         print "Pretending to process"
...         raise RuntimeError("Pretend I had an error")
...     except:
...         print "Pretending to close file"
...         errStatus = 1
...     if errStatus:
...         print "Reraising Error"
...         raise
... 	
>>> fileOp()
Pretending to open a file
Pretending to process
Pretending to close file
Reraising Error
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
  File "<interactive input>", line 6, in fileOp
RuntimeError: Pretend I had an error
>>>




More information about the Python-list mailing list