[Python-Dev] Exception masking/chaining

Walter Dörwald walter@livinglogic.de
Wed, 11 Jun 2003 16:05:40 +0200


Brett C. wrote:

> Walter Dörwald wrote:
> 
> [...]
>> but we could add a new feature to that: Add a new exception
>> subclass named Info that can be used to wrap exceptions without
>> influencing the type of the exception raised. This could be used
>> by code higher up in the call chain to add information to the
>> exception without changing the type that gets caught in the except
>> statement. For example filter() could be changed to add information
>> about the iteration index where the exception happened:
>>
>> class spam:
>>    def __getitem__(self, index):
>>       if index==42:
>>          raise TypeError
>>       return None
>>
>> x = filter(None, spam())
>>
>> this might give:
>>
>> Traceback (most recent call last):
>>   File "spam.py", line 8, in ?
>>     x = filter(None, foo())
>>   File "spam.py", line 4, in __getitem__
>>     raise TypeError("ouch")
>> TypeError: ouch
>> Info: in filter() at index 42
>>
> 
> So have a function that takes the current exception, stores it as an 
> attribute of a new one,

This could be done automatically, i.e. whenever you call
PyErr_SetString() etc. the currently active exception will be normalized
and put into a fourth global variable (exc_cause). In Python code
whenever a exception handler raises a new exception the exception
that is currently handled could be set as the cause for this
exception automatically by the raise statement.

> and have exception-handling code no of the 
> possible existence of the attribute and print out the info if it exists?

I'd say, the attribute should always be there, but should be initialized
to None in the Exception constructor (they same should probably be done
for the traceback attribute).

Bye,
    Walter Dörwald