Re-raising exceptions with modified message

Neil Cerutti horpner at yahoo.com
Thu Jul 5 15:11:58 EDT 2007


On 2007-07-05, Christoph Zwerschke <cito at online.de> wrote:
> Neil Cerutti wrote:
>> The documentation for BaseException contains something that might
>> be relevant:
>> 
>>    [...] If more data needs to be attached to the exception,
>>    attach it through arbitrary attributes on the instance. All
>>
>> Users could get at the extra info you attached, but it wouldn't
>> be automatically displayed by the interpreter.
>
> Yes, that's the problem here. It wouldn't be displayed
> automatically and the users must be aware of this attribute.
> I'd like to have a more transparent solution.

You ought to be able to use the third arg of raise to raise a new
exception as if it were from the previous location, but now with
a new message.

You may need the traceback module to get at the error message, if
trying to read e.message can fail.

Something like this mess here: ;)

   ...
   except Exception, e:
     etype, evalue, etb = sys.exc_info()
     ex = traceback.format_exception_only(etype, evalue)
     message = ex[0].partition(':')[2].strip()
     raise etype, message+". Sorry!", etb

Note that the above will break for SyntaxError (who's message
contains more than one line) and any kind of exception that
doesn't inherit from Exception.

You might need some crufty try, finally to avoid having a
circular reference hang around, according to the docs for
sys.exc_info.

-- 
Neil Cerutti



More information about the Python-list mailing list