Instance Exception Oddity: Implicit and Explicit not the same?

RT Lange whiteywidow at yahoo.com
Tue Dec 9 05:58:36 CET 2003


On Sun, 07 Dec 2003 18:39:54 +0100, Peter Otten <__peter__ at web.de> wrote:

> RT Lange wrote:
>
>>>>> class E1(Exception): pass
>>
>>>>> class E2(E1): pass
>>
>>>>> i = E2('foo')
>>>>> raise E1(i)
>> Traceback (most recent call last):
>>    File "<pyshell#5>", line 1, in ?
>>      raise E1(i)
>> E1: foo
>>>>> raise E1, i
>> Traceback (most recent call last):
>>    File "<pyshell#6>", line 1, in ?
>>      raise E1, i
>> E2: foo
>>>>>
>>
>> Is there a reason the exception type is not the same?
>> Is this behavior something that should be expected?
>
> This is interesting. I thought of
>
> raise E, o # 1
>
> and
>
> raise E(o) # 2
>
> as equivalent. Well, until today:
>
> "If the first object is a class, it becomes the type of the exception. 
> The
> second object is used to determine the exception value: If it is an
> instance of the class, the instance becomes the exception value. If the
> second object is a tuple, it is used as the argument list for the class
> constructor; if it is None, an empty argument list is used, and any other
> object is treated as a single argument to the constructor. The instance 
> so
> created by calling the constructor is used as the exception value."
>
> (quoted from http://www.python.org/doc/current/ref/raise.html)
>
> So, if isinstance(o, E), the first form is indeed equivalent to
>
> raise o
>
but if o is an instance of an E subclass (hence isinstance(o, E) is still 
true),
shouldn't the first form raise an exception with type E (not E's subclass)
and value o?



-- 
Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/




More information about the Python-list mailing list