Instance Exception Oddity: Implicit and Explicit not the same?

Peter Otten __peter__ at web.de
Sun Dec 7 12:39:54 EST 2003


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

and your code works as advertised.


Peter







More information about the Python-list mailing list