Catch and name an exception in Python 2.5 +

S

Steven D'Aprano

In Python 3, you can catch an exception and bind it to a name with:

try:
...
except ValueError, KeyError as error:
pass

In Python 2.5, that is written:

try:
...
except (ValueError, KeyError), error:
pass

and the "as error" form gives a SyntaxError.

Python 2.6 and 2.7 accept either form.

Is there any way to catch an exception and bind it to a name which will work
across all Python versions from 2.5 onwards?

I'm pretty sure there isn't, but I thought I'd ask just in case.
 
T

Thomas Jollans

In Python 3, you can catch an exception and bind it to a name with:

try:
...
except ValueError, KeyError as error:
pass

In Python 2.5, that is written:

try:
...
except (ValueError, KeyError), error:
pass

and the "as error" form gives a SyntaxError.

Python 2.6 and 2.7 accept either form.

Is there any way to catch an exception and bind it to a name which will work
across all Python versions from 2.5 onwards?

I'm pretty sure there isn't, but I thought I'd ask just in case.

It's not elegant, and I haven't actually tested this, but this should work:

try:
...
except (ValueError, KeyError):
error = sys.exc_info()[2]
 
S

Steven D'Aprano

Thomas said:
On 26/08/11 21:56, Steven D'Aprano wrote:
Is there any way to catch an exception and bind it to a name which will
work across all Python versions from 2.5 onwards?

I'm pretty sure there isn't, but I thought I'd ask just in case.

It's not elegant, and I haven't actually tested this, but this should
work:

try:
...
except (ValueError, KeyError):
error = sys.exc_info()[2]

Great! Thanks for that, except I think you want to use [1], not [2].
 
T

Thomas Jollans

Thomas said:
On 26/08/11 21:56, Steven D'Aprano wrote:
Is there any way to catch an exception and bind it to a name which will
work across all Python versions from 2.5 onwards?

I'm pretty sure there isn't, but I thought I'd ask just in case.

It's not elegant, and I haven't actually tested this, but this should
work:

try:
...
except (ValueError, KeyError):
error = sys.exc_info()[2]

Great! Thanks for that, except I think you want to use [1], not [2].

Ah, yes. Of course.
 

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,769
Messages
2,569,582
Members
45,062
Latest member
OrderKetozenseACV

Latest Threads

Top