Exception Handling in Python 3

Steve Holden steve at holdenweb.com
Sun Oct 24 08:36:04 EDT 2010


On 10/24/2010 2:22 AM, Lawrence D'Oliveiro wrote:
> In message <mailman.176.1287896531.2218.python-list at python.org>, Steve 
> Holden wrote:
> 
>> 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 what exactly is the problem? Exceptions are so easy to get wrong, it’s 
> just trying to report more info in a complicated situation to help you track 
> down the problem. Why is that bad?
> 
>> 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]
> 
> I don’t see why. Presumably if you caught the exception in an outer try-
> except clause, you would pick up your AttributeError, not the KeyError, 
> right? Which is what you want, right?

Yes, *if the exception is caught* then it doesn't make any difference.
If the exception creates a traceback, however, I maintain that the
additional information is confusing to the consumer (while helpful to
the debugger of the consumed code).

I don't want people to think this is a big deal, however. It was just an
"eh?" that I thought must mean I was missing some way of suppressing the
additional traceback. Peter Otten has already provided a solution using
sys.except_hook().

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