Re-raising exceptions with modified message

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon Jul 16 13:14:25 EDT 2007


En Mon, 16 Jul 2007 13:50:50 -0300, fumanchu <fumanchu at amor.org> escribió:

> On Jul 15, 2:55 am, Christoph Zwerschke <c... at online.de> wrote:
>> Here is a simple solution, but it depends
>> on the existence of the args attribute that
>> "will eventually be deprecated" according
>> to the docs
>
> If you don't mind using .args, then the solution is usually as simple
> as:
>
>
> try:
>     Thing.do(arg1, arg2)
> except Exception, e:
>     e.args += (Thing.state, arg1, arg2)
>     raise
>
>
> No over-engineering needed. ;)

If you read enough of this long thread, you'll see that the original  
requirement was to enhance the *message* displayed by a normal traceback -  
the OP has no control over the callers, but wants to add useful  
information to any exception.
Your code does not qualify:

py> try:
...   open("a file that does not exist")
... except Exception,e:
...   e.args += ("Sorry",)
...   raise
...
Traceback (most recent call last):
   File "<stdin>", line 2, in <module>
IOError: [Errno 2] No such file or directory: 'a file that does not exist'
py> try:
...   x = u"á".encode("ascii")
... except Exception,e:
...   e.args += ("Sorry",)
...   raise
...
Traceback (most recent call last):
   File "<stdin>", line 2, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe1' in  
position 0:
ordinal not in range(128)

-- 
Gabriel Genellina




More information about the Python-list mailing list