Questions on exceptions

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Mon Aug 21 04:40:59 EDT 2006


In <1156146013.939619.102570 at i3g2000cwc.googlegroups.com>, sc_wizard29
wrote:

> Also, can someone explain me why there is no try...except...finally
> statement ?

AFAIK historical reasons.  There where some concerns about ambiguity.  But
in Python 2.5 this form will become legal syntax.

> For example, the following code snippet is not valid, but
> what would be the correct python way to do it ?
> 
> myFile = open('file.txt') # assume file exists
> try:
> 	for nextLine in file:
>         	nextLine = nextLine.rstrip('\n');print "line = " + nextLine
> except IOError:
> 	print "Error while reading from file"
> finally:
> 	myFile.close

You forgot the parenthesis for the `close()` method.

In Python <=2.4 you have to nest:

try:
    try:
       pass
    except Error:
       pass
finally:
    pass

Maybe you are interested in the new (Python 2.5) ``with`` statement too:

http://docs.python.org/dev/ref/with.html

And the style guide: http://www.python.org/dev/peps/pep-0008/ (because you
used Java naming conventions)

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list