473,387 Members | 1,520 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

confusion around CustomException example in 'Python in a Nutshell'

In Martinelli's Nutshell book in the Exceptions chapter there is an
example of a custom exception class (pg.112) that I am trying to
implement without success. The custom exception class example pulls
sys.exc_info() into an attribute and I am assuming that the attribute
would then contain the raised exception info in a tuple (admittedly I
could be assuming erroneously).

class LinuxDriverError(Exception):
def __init__(self, *args):
Exception.__init__(self, *args)
self.message = args[0]
self.wrapped_exc = sys.exc_info()

try:
raise LinuxDriverError, "raising Cain!"
except CustomException, error:
print error.message
print error.wrapped_exc

# just checking
print "sys.exc_info(): ", sys.exc_info()

If I run the above code I get the following output:

Just raising Cain!
wrapped_exc: (None, None, None)
sys.exc_info(): (<class __main__.LinuxDriverError at 0xf6f774dc>,
<__main__.LinuxDriverError instance at 0xf6f74bec>, <traceback object
at 0xf6f7193c>)

I do not understand why the wrapped_exc attribute contains no objects.

I am running 2.3.4 on a fedora core 3 box.

thanks,

erick

Jul 18 '05 #1
4 1581
I don't know the mentioned book, but if you rewrite like:
import sys
class LinuxDriverError(Exception): .... def __init__(self, *args):
.... Exception.__init__(self, *args)
.... self.message = args[0]
....
.... def __str__(self):
.... return str(sys.exc_info())
.... def test(): .... raise LinuxDriverError, "raising Cain!"
.... try: .... test()
.... except LinuxDriverError, error:
.... print error
....
(<class __main__.LinuxDriverError at 0x401e305c>,
<__main__.LinuxDriverError instance at 0x401deb6c>, <traceback object
at 0x401df20c>) # just checking

.... print "sys.exc_info(): ", sys.exc_info()

This gets what you probably expect, the way you do it there is no
traceback object when you print it

Jul 18 '05 #2
er**********@comcast.net wrote:
In Martinelli's Nutshell book in the Exceptions chapter there is an
example of a custom exception class (pg.112) that I am trying to
implement without success. The custom exception class example pulls
sys.exc_info() into an attribute and I am assuming that the attribute
would then contain the raised exception info in a tuple (admittedly I
could be assuming erroneously).

class LinuxDriverError(Exception):
def __init__(self, *args):
Exception.__init__(self, *args)
self.message = args[0]
self.wrapped_exc = sys.exc_info()

try:
raise LinuxDriverError, "raising Cain!"
except CustomException, error:
print error.message
print error.wrapped_exc

# just checking
print "sys.exc_info(): ", sys.exc_info()

If I run the above code I get the following output:

Just raising Cain!
wrapped_exc: (None, None, None)
sys.exc_info(): (<class __main__.LinuxDriverError at 0xf6f774dc>,
<__main__.LinuxDriverError instance at 0xf6f74bec>, <traceback object
at 0xf6f7193c>)

I do not understand why the wrapped_exc attribute contains no objects.


Because at the time you create the exception there is
no "current exception" as seen from the point of view
of sys.exc_info().

Given the way this class was written, it is clearly
intended to be raised from within an "except" statement
as a result of another exception having been caught.

Try this instead:

try:
try:
1/0
except:
raise LinuxDriverError, 'raising Cain!'
except Exception, ex:
print ex.wrapped_exc
By the way, the code you show is probably not what you
were actually running anyway... you caught a
"CustomException" but the LinuxDriverError is not
a subclass of that class so it wouldn't/shouldn't
have been caught.

-Peter
Jul 18 '05 #3

Peter Hansen wrote:
er**********@comcast.net wrote:
In Martinelli's Nutshell book in the Exceptions chapter there is an
example of a custom exception class (pg.112) that I am trying to
implement without success. The custom exception class example pulls sys.exc_info() into an attribute and I am assuming that the attribute would then contain the raised exception info in a tuple (admittedly I could be assuming erroneously).

class LinuxDriverError(Exception):
def __init__(self, *args):
Exception.__init__(self, *args)
self.message = args[0]
self.wrapped_exc = sys.exc_info()

try:
raise LinuxDriverError, "raising Cain!"
except CustomException, error:
print error.message
print error.wrapped_exc

# just checking
print "sys.exc_info(): ", sys.exc_info()

If I run the above code I get the following output:

Just raising Cain!
wrapped_exc: (None, None, None)
sys.exc_info(): (<class __main__.LinuxDriverError at 0xf6f774dc>,
<__main__.LinuxDriverError instance at 0xf6f74bec>, <traceback object at 0xf6f7193c>)

I do not understand why the wrapped_exc attribute contains no
objects.
Because at the time you create the exception there is
no "current exception" as seen from the point of view
of sys.exc_info().

Given the way this class was written, it is clearly
intended to be raised from within an "except" statement
as a result of another exception having been caught.

Try this instead:

try:
try:
1/0
except:
raise LinuxDriverError, 'raising Cain!'
except Exception, ex:
print ex.wrapped_exc
This clears the fog a little.
By the way, the code you show is probably not what you
were actually running anyway... you caught a
"CustomException" but the LinuxDriverError is not
a subclass of that class so it wouldn't/shouldn't
have been caught.
<classic keyboard fumbling> What I am trying to do is get information
from a raised custom exception. I am catching the exception in a
main() function but it was actually raised in a separate module
function. It would be nice if I could print out where the exception
was raised from (module.function name + line number).

-------------------------
def some_module_function():
if something_bad:
raise LinuxDriverError, "raising.."
---------------------------

def main():
try:
mymodule.some_module_function()
except LinuxDriverError, error:
print error.message
print error.from_where

Thanks,

--Erick


-Peter


Jul 18 '05 #4
er**********@comcast.net wrote:
<classic keyboard fumbling> What I am trying to do is get information
from a raised custom exception. I am catching the exception in a
main() function but it was actually raised in a separate module
function. It would be nice if I could print out where the exception
was raised from (module.function name + line number).


Ah, good. Exactly what the useful functions in the
'traceback' module are intended for, if I understand
your meaning...

If doing "traceback.print_exc()" is printing the
information you want (in a traceback that has much
more than what you say you want), then you can use
the other functions in that module, and methods in
the 'traceback' objects themselves (the third item
in the tuple returned by sys.exc_info()), will
give you all you could ever want...

Google can help you find examples of usage as well,
in the archives for this group.

-Peter
Jul 18 '05 #5

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

Similar topics

220
by: Brandon J. Van Every | last post by:
What's better about Ruby than Python? I'm sure there's something. What is it? This is not a troll. I'm language shopping and I want people's answers. I don't know beans about Ruby or have...
14
by: Eduardo Patto Kanegae | last post by:
Hello, I have been programming with Visual Basic and PHP in the last 5 years and some folks had recommended Python a free language.... I had looked for a Python book to start up but found many...
0
by: python newbie | last post by:
Ok, I am struggling with this setup.py. My python script happens to use the mxBase library, specifically the mx.DateTime package. That's the only "third party" package I use. I've gone through...
7
by: Porky Pig Jr | last post by:
Hello, I"m still learning Python, but going through the Ch 5 OOP of Nutshell book. There is discussion on __slots__, and my understanding from reading this section is that if I have a class...
14
by: Tuang | last post by:
Does anyone (esp. Alex, if you're listening) know if there is an update of Python in a Nutshell coming for Python 2.4?
38
by: Grant Edwards | last post by:
In an interview at http://acmqueue.com/modules.php?name=Content&pa=showpage&pid=273 Alan Kay said something I really liked, and I think it applies equally well to Python as well as the languages...
3
by: nate | last post by:
Hello everyone, Can anyone recommend python text progression from me. Assuming I have no knowledge of python which books should I progress through? I prefer published books that I can actually...
9
by: Katie Tam | last post by:
I am new to this filed and begin to learn this langague. Can you tell me the good books to start with ? Katie Tam Network administrator http://www.linkwaves.com/main.asp...
5
by: W. eWatson | last post by:
I read an Amazon of Python in a Nutshell. The first edition is supposedly much like the web site. What web site? The second edition apparently adds more to the book than the web site. -- Wayne...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
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...
0
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,...
0
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...

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.