473,800 Members | 2,615 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Instance Exception Oddity: Implicit and Explicit not the same?

>>> 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?
--
Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/
Jul 18 '05 #1
6 1564
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

Jul 18 '05 #2
In article <op************ **@newgroups.be llsouth.net>,
RT Lange <wh*********@ya hoo.com> 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


<scratch head> Why are you passing an exception instance to the
constructor for a different exception?
--
Aahz (aa**@pythoncra ft.com) <*> http://www.pythoncraft.com/

Weinberg's Second Law: If builders built buildings the way programmers wrote
programs, then the first woodpecker that came along would destroy civilization.
Jul 18 '05 #3
On Sun, 07 Dec 2003 18:39:54 +0100, Peter Otten <__*******@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/
Jul 18 '05 #4
RT Lange wrote:
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?


Again:

"If it is an instance of the class, the *instance* *becomes* the *exception*
*value*"

Or, directly from the source:

/* if the value was not an instance, or is not an instance
whose class is (or is derived from) type, then use the
value as an argument to instantiation of the type
class.
*/

(comment in function PyErr_Normalize Exception() in error.c)

As clear as you can get. I cannot comment on the rationale of that design
decision, though. I would replace the

raise E, args # disallow in 3.0?

form completely with

raise E(args)

which would avoid the ambiguity altogether.
Peter

PS: I think you owe me an answer to Aahz' pending question now :-)


Jul 18 '05 #5
Peter Otten <__*******@web. de> wrote in message news:<br******* *****@news.t-online.com>...
"If it is an instance of the class, the *instance* *becomes* the *exception*
*value*"

this says nothing about the *type* of exception, just the *value*.
"6.9 The raise statement
....The first two objects are used to determine the type and value of
the exception.
If the first object is an instance, the TYPE of the exception is the
class of the instance, the instance itself is the VALUE, and the
second object must be None."
class E(Exception): pass i = E('foo')
try: raise i
except:
print sys.exc_info()[:2]
(<class __main__.E at 0x00A88090>, <__main__.E instance at
0x00A5A850>)

*makes perfect sense*

"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."
try: raise Exception, i #first object is a class: becomes the type
#second object instance of (sub)class: becomes the valu
except:
print sys.exc_info()[:2]
(<class __main__.E at 0x00A88090>, <__main__.E instance at
0x00A5A850>)

*hmmm "Exception" did NOT become the TYPE of the exception*

As for why I was passing an exception instance to the
constructor for a different exception...jus t pointing out the
nonequivalence of the two forms.
Why would someone want to do this? Don't ask me.
I only use string exceptions. :)

RT
Jul 18 '05 #6
wh*********@yah oo.com (rt lange) wrote in message news:<b7******* *************** ***@posting.goo gle.com>...
*hmmm "Exception" did NOT become the TYPE of the exception*


One could argue that Exception is in fact the type of the exception.
import sys
class E(Exception): .... pass
.... try:

.... raise Exception, i
.... except:
.... print isinstance(sys. exc_info()[1], Exception)
....
True

It just so happens that the exception is also of type E. In fact
'except Exception:' will also catch the exception.

--
Shalabh
Jul 18 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
2356
by: Fahd Khan | last post by:
Hi team! While troubleshooting a crash I had while using BitTorrent where the torrent's target file names didn't fall into the ascii range I was playing around in the interpreter and noticed this behaviour: >>> u'\u12345' + 'foo' u'\u12345foo' >>> u'\u12345' u'foo' u'\u12345foo' >>> u'\u12345' + u'foo'.encode('ascii') u'\u12345foo'
8
1682
by: Lonnie Princehouse | last post by:
In a recent post, Michele Simionato asked about resumable (or re-entrant) exceptions, the basic idea being that when raised and uncaught, these exceptions would only propagate backwards through a limited number of frames before being implicitly ignored. Alex Martelli pointed out that resumable exceptions are difficult to implement, and that the need for them isn't pressing because it's pretty easy to write a program with explicit error...
11
1880
by: Johan | last post by:
Hi Can somebody explain to me why I get this warning message and how I can solve this warning message. Thanks a lot Johan In member function `void
23
2448
by: Allin Cottrell | last post by:
Thomas Heinz wrote (in re. gcc compilation of this erroneous program): $ cat test.c int f(int); int f(); int f() {return 0;} int main (void) { return 0; }
9
2090
by: Girish | last post by:
Im trying to understand implicit type conversions from object -> string and vice versa. I have two classes, one Driver and one called StringWrapper. These are just test classes that try and emulate the pattern im trying to follow in an existing project. These are my steps: 1) I have a method "printMe" existing in the application which originally used to take in a string. This method is static and sits in the Driver
2
2358
by: kpax | last post by:
Hi, While debugging my application when an explicit exception is thrown by me (or an implicit exception is thrown internally) which is not handled anywhere in the stack, the execution breaks as expected but I can not continue. I try start the execution and go back to running mode, but it always comes to the same line where the exception is first thrown.
36
3637
by: Chad Z. Hower aka Kudzu | last post by:
I have an implicit conversion set up in an assembly from a Stream to something else. In C#, it works. In VB it does not. Does VB support implicit conversions? And if so any idea why it would work in a C# program but not VB? -- Chad Z. Hower (a.k.a. Kudzu) - http://www.hower.org/Kudzu/ "Programming is an art form that fights back"
17
2519
by: arindam.mukerjee | last post by:
I was running code like: #include <stdio.h> int main() { printf("%f\n", 9/5); return 0; }
3
2473
by: Jess | last post by:
Hello, I can perform implicit conversion through constructor, like class A{ public: A(int x):a(x){}; int a; };
0
9551
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10504
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10274
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10033
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9085
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7576
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6811
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5606
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2945
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.