Exception Handling in Python 3

Steve Holden steve at holdenweb.com
Sun Oct 24 01:01:43 EDT 2010


I was somewhat surprised to discover that Python 3 no longer allows an
exception to be raised in an except clause (or rather that it reports it
as a separate exception that occurred during the handling of the first).

So the following code:

>>> d = {}
>>> try:
...     val = d['nosuch']
... except:
...     raise AttributeError("No attribute 'nosuch'")
...

Give the traceback I expected and wanted in Python 2:

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
AttributeError: No attribute 'nosuch'

but in Python 3.1 the traceback looks like this:

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
KeyError: 'nosuch'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
AttributeError: No attribute 'nosuch'

Modifying the code a little allows me to change the error message, but
not much else:

>>> d = {}
>>> try:
...     val = d['nosuch']
... except KeyError as e:
...     raise AttributeError("No attribute 'nosuch'") from e
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
KeyError: 'nosuch'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
AttributeError: No attribute 'nosuch'
>>>

In a class's __getattr__() method this means that instead of being able
to say

    try:
        value = _attrs[name]
    except KeyError:
        raise AttributeError ...

I am forced to write

    if name not in _attrs:
        raise AttributeError ...
    value = _attrs[name]

which requires an unnecessary second lookup on the attribute name. What
is the correct paradigm for this situation?

regards
 Steve
-- 
Steve Holden           +1 571 484 6266   +1 800 494 3119
PyCon 2011 Atlanta March 9-17       http://us.pycon.org/
See Python Video!       http://python.mirocommunity.org/
Holden Web LLC                 http://www.holdenweb.com/




More information about the Python-list mailing list