Re-raising exceptions with modified message

Neil Cerutti horpner at yahoo.com
Fri Jul 6 06:58:36 EDT 2007


On 2007-07-06, Alex Popescu <the.mindstorm.mailinglist at gmail.com> wrote:
> On Jul 6, 4:20 am, Christoph Zwerschke <c... at online.de> wrote:
>> Alex Popescu wrote:
>> > Probably the simplest solution would be to create a new exception and
>> > wrapping the old one and the additional info. Unfortunately, this
>> > may have a huge impact on 3rd party code that was catching the
>> > original exception. So, I think you should create an utility
>> > factory-like function that is either creating a new exception
>> > instance as the one caught and with the additional information,
>>
>> Right, I have gone with that (see the example with the PoliteException
>> class somewhere below).
>>
>> > or an utility that knows how to modify the caught exception according
>> > to its type.
>>
>> I guess you mean something like this (simplified):
>>
>> except Exception, e:
>>      if getattr(e, 'reason'):
>>          e.reason += "sorry"
>>      else:
>>          e.message += "sorry"
>>
>> The problem is that these attribute names are not standardized and can
>> change between Python versions. Not even "args" is sure, and if a class
>> has "message" it does not mean that it is displayed. Therefore I think
>> the first approach is better.
>>
>> > In the first case you will need somehow to tell to the new instance
>> > exception the real stack trace, because by simply raising
>> > a new one the original stack trace may get lost.
>>
>> Yes, but thats a different problem that is easy to solve.
>
> Yeah maybe for a python guy, but I am a newbie. I would really
> appreciate if you can show in this thread how this can be done
> in Python.

Chech out the docs for sys.exc_info(), and for the raise
statement.

When handling an exception, you can rethrow a different
exception, but with the same traceback, by using the three-arg
version of raise.

See one of my earlier posts in this thread for a working example
(although it didn't solve Chris's problem).

-- 
Neil Cerutti



More information about the Python-list mailing list