Combined error message for user defined exceptions

Steve Purcell stephen_purcell at yahoo.com
Tue Feb 27 11:00:12 EST 2001


guido-dot-treutwein-at-nbg-dot-siemens-dot-de.cut-here at no.spam wrote:
> class excMyError(TypeError):
>     def __str__(self):
>         return "My generic error"
> #... and later ...
> raise excMyError, "additional info"
> 
> What I want is to merge the generic exception text with the additional
> information just like
> 
> NameError: There is no variable named 'undefvar'

There may be nicer ways to do it, but if you promise to always throw the
exception with only one argument, you can do the following:-


>>> class MyException(TypeError):
...     def __str__(self):
...        return "there is no variable named '%s'" % self.args[0]
... 
>>> raise MyException, 'foobar'
Traceback (innermost last):
  File "<stdin>", line 1, in ?
__main__.MyException: there is no variable named 'foobar'
>>> 


But even more simply, you can set the message exactly in the place where you
throw the exception, which is often the most appropriate option:


>>> class MyException(TypeError): pass
... 
>>> raise MyException, "no such variable 'foobar'"
Traceback (innermost last):
  File "<stdin>", line 1, in ?
__main__.MyException: no such variable 'foobar'
>>> 


Best wishes,

-Steve


-- 
Steve Purcell, Pythangelist
Get testing at http://pyunit.sourceforge.net/
Get servlets at http://pyserv.sourceforge.net/
"Even snakes are afraid of snakes." -- Steven Wright




More information about the Python-list mailing list