how to get a return value from an exception ?

Eric Brunel eric.brunel at pragmadev.com
Thu Jul 25 10:23:27 EDT 2002


Shagshag13 wrote:
> hello,
> 
> i need to raise an exception which "carry" some data... i think that it's
> something like :
> 
> class MyException(Exception):
> 
>  def __init__(self, *args):
>   Exception.__init__(self, args)
> 
>>>> raise MyException('one', 2, 'three')
> Traceback (most recent call last):
>   File "<pyshell#66>", line 1, in ?
>     raise MyException('one', 2, 'three')
> MyException: ('one', 2, 'three')
> 
> but them how to access to 'one', 2, and 'three' ?

Just do the following:

class MyException(Exception):
  def __init__(self, arg1, arg2):
    Exception.__init__(self)
    self.arg1 = arg1
    self.arg2 = arg2

try:
  raise MyException('one', 2)
except MyException, ex:
  print ex.arg1, ex.arg2

> it's ok if i do it like in "dive in python"
> 
>>>> class MyError(Exception):
> def __init__(self, value):
>     self.value = value
> def __str__(self):
>     return `self.value`
> 
> but here what does the `` stand for ?

It's an equivalent for repr(...): it converts its argument to its 
"canonical" string representation. I don't know the original intent of this 
code, but I suppose it was just to actually see what was the value and its 
type when the exception ends up in a traceback.

HTH
-- 
- Eric Brunel <eric.brunel at pragmadev.com> -
PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com



More information about the Python-list mailing list