try/except/else/finally problem

E

Ed Jensen

I'm using:

Python 2.3.2 (#1, Oct 17 2003, 19:06:15) [C] on sunos5


And I'm trying to execute:

#! /usr/bin/env python

try:
f = file('test.txt', 'r')
except IOError:
print 'except'
else:
print 'else'
finally:
print 'finally'


And the results are:

File "./test.py", line 9
finally:
^
SyntaxError: invalid syntax


What am I doing wrong?

Thanks in advance for any help.
 
P

Peter Otten

Ed said:
I'm using:

Python 2.3.2 (#1, Oct 17 2003, 19:06:15) [C] on sunos5


And I'm trying to execute:

#! /usr/bin/env python

try:
f = file('test.txt', 'r')
except IOError:
print 'except'
else:
print 'else'
finally:
print 'finally'


And the results are:

File "./test.py", line 9
finally:
^
SyntaxError: invalid syntax


What am I doing wrong?

You need Python 2.5 for that to work. In older Python versions you have to
nest try...except...else and try...finally.

Peter
 
S

Sebastian Wiesner

[ Ed Jensen said:
try:
f = file('test.txt', 'r')
except IOError:
print 'except'
else:
print 'else'
finally:
print 'finally'


And the results are:

File "./test.py", line 9
finally:
^
SyntaxError: invalid syntax

A finally block isn't allowed to appear together with an except block for
releases previous to 2.5. You need to split your exception handling into
two separate blocks.

--
Freedom is always the freedom of dissenters.
(Rosa Luxemburg)

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v2.0.4 (GNU/Linux)

iD8DBQBGg/iun3IEGILecb4RAutfAJwPOVb9HcdtQh9Lr8oCp10PnAqjLQCfTILh
TbU0DcUKHMl0VVHf1g8WGsQ=
=cVzM
-----END PGP SIGNATURE-----
 
E

Ed Jensen

You need Python 2.5 for that to work. In older Python versions you have to
nest try...except...else and try...finally.

Thanks Peter.

Given the code above, can you show me what that would look like? The
nested version, that is.
 
P

Peter Otten

Ed said:
Thanks Peter.

Given the code above, can you show me what that would look like? The
nested version, that is.

try:
try:
f = file("test.txt", "r")
except IOError:
print "except"
else:
print "else"
finally:
print "finally"

Peter
 
B

Ben Finney

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

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,185
Members
46,736
Latest member
AdolphBig6

Latest Threads

Top