[Tutor] "=" invalid syntax ?

Lloyd Kvam pythontutor at venix.com
Sun Feb 1 21:36:31 EST 2004


Daniel Ehrenberg wrote:

>>try/except and try/finally are two different forms. 
>>There is no try/except/finally.
>>
>>(thanks to Alex Martelli) it should look more like:
>>
>>try:
>>     try:
>>         fi = open('test.py', 'r')
>>     except IOError:
>>         print "Can't open file for reading."
>>     else:
>>         for line in fi:
>>             print line
>>finally:
>>     fi.close()
>>
>>The else is a convenient to limit the scope of the
>>try statement.
>>
>>The exceptions chapter of "Python in a Nutshell" has
>>very lucid descriptions
>>of exception handling strategies.
> 
> 
> I'm probably making some big mistake again, but if
> you're using both except and else, why not just write:
> 
> try:
>     fi = open('test.py', 'r')
> except IOError:
>     print "Can't open file for reading."
> else:
>     for line in fi:
>         print line
> 
> fi.close()
> 
> Daniel Ehrenberg

In actual practise, that is what I'd write.  I was just showing
the general approach to having finally and except for the same
block of code.

Typically try/finally encloses a "logically" large block of
cade and simply guarantees that a log entry will get written or
that a file or other resource will get closed.

try/except usually covers small blocks of code.
It also provides general recovery control for applications that
must continue after an exception is raised.

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582




More information about the Tutor mailing list