how to get a return value from an exception ?

Shagshag13 shagshag13 at yahoo.fr
Thu Jul 25 10:34:20 EDT 2002


"Eric Brunel" <eric.brunel at pragmadev.com> a écrit dans le message de news: ahp184$c9v$1 at wanadoo.fr...
> 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

thanks ! i was missing that "ex" was an instance of MyException class !
so :

try:
    raise MyException('one', 2, '3')
except MyException, ex:
    print type(ex)
    ex[0][0]

<type 'instance'>
'one'

i had another questions :

* if exceptionB and exceptionC subclass from exceptionA, if i raise exceptionB i could still catch it as it was ExceptionA ?
* is it a correct statement ? :
try:
    #do
except exceptionB:
    #do 1
except exceptionC:
    #do 2
except exceptionA:
    #do else

thanks,

s13.







More information about the Python-list mailing list