Exception Messages

W

Wanderer

How do you get Exceptions to print messages? I have an exception defined like this

class PvCamError(Exception):
def __init__(self, msg):
self.msg = msg

But when the error is raised I get this:

Traceback (most recent call last):
File "C:\Python27\lib\site-packages\ipython-0.12.1-py2.7.egg\IPython\core\interactiveshell.py", line 2538, in run_code
exec code_obj in self.user_global_ns, self.user_ns
File "<ipython-input-1-fb48da797583>", line 1, in <module>
import S477Test
File "U:\workspace\camera\src\S477Test.py", line 13, in <module>
camera.getSerialNum()
File "U:\workspace\camera\src\S477.py", line 131, in getSerialNum
num = self.pl.getParamValue(pvcamConstants.PARAM_HEAD_SER_NUM_ALPHA)
File "U:\workspace\camera\src\pvcam.py", line 261, in getParamValue
raise PvCamError("Unhandled Type: {0}".format(attype))
PvCamError

Why wasn't the message printed out?
 
M

MRAB

How do you get Exceptions to print messages? I have an exception defined like this

class PvCamError(Exception):
def __init__(self, msg):
self.msg = msg

But when the error is raised I get this:

Traceback (most recent call last):
File "C:\Python27\lib\site-packages\ipython-0.12.1-py2.7.egg\IPython\core\interactiveshell.py", line 2538, in run_code
exec code_obj in self.user_global_ns, self.user_ns
File "<ipython-input-1-fb48da797583>", line 1, in <module>
import S477Test
File "U:\workspace\camera\src\S477Test.py", line 13, in <module>
camera.getSerialNum()
File "U:\workspace\camera\src\S477.py", line 131, in getSerialNum
num = self.pl.getParamValue(pvcamConstants.PARAM_HEAD_SER_NUM_ALPHA)
File "U:\workspace\camera\src\pvcam.py", line 261, in getParamValue
raise PvCamError("Unhandled Type: {0}".format(attype))
PvCamError

Why wasn't the message printed out?
You didn't add a __str__ method:

class PvCamError(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
 
M

MRAB

Wouldn't PvCamError inherit __str__() from Exception?
Yes, but you've put the message in msg, and Exception doesn't have that
attribute.

An alternative approach would be:

class PvCamError(Exception):
pass
 
W

Wanderer

Yes, but you've put the message in msg, and Exception doesn't have that

attribute.

That's weird. I got this Exception class definition idea from this post by Guido van Rostrum, Where he gives this main function to look like

import sys
import getopt

class Usage(Exception):
def __init__(self, msg):
self.msg = msg

def main(argv=None):
if argv is None:
argv = sys.argv
try:
try:
opts, args = getopt.getopt(argv[1:], "h", ["help"])
except getopt.error, msg:
raise Usage(msg)
# more code, unchanged
except Usage, err:
print >>sys.stderr, err.msg
print >>sys.stderr, "for help use --help"
return 2

if __name__ == "__main__":
sys.exit(main())




http://www.artima.com/weblogs/viewpost.jsp?thread=4829
 
W

Wanderer

Yes, but you've put the message in msg, and Exception doesn't have that

attribute.

That's weird. I got this Exception class definition idea from this post by Guido van Rostrum, Where he gives this main function to look like

import sys
import getopt

class Usage(Exception):
def __init__(self, msg):
self.msg = msg

def main(argv=None):
if argv is None:
argv = sys.argv
try:
try:
opts, args = getopt.getopt(argv[1:], "h", ["help"])
except getopt.error, msg:
raise Usage(msg)
# more code, unchanged
except Usage, err:
print >>sys.stderr, err.msg
print >>sys.stderr, "for help use --help"
return 2

if __name__ == "__main__":
sys.exit(main())




http://www.artima.com/weblogs/viewpost.jsp?thread=4829
 
W

Wanderer

Yes, but you've put the message in msg, and Exception doesn't have that



That's weird. I got this Exception class definition idea from this post by Guido van Rostrum, Where he gives this main function to look like



import sys

import getopt



class Usage(Exception):

def __init__(self, msg):

self.msg = msg



def main(argv=None):

if argv is None:

argv = sys.argv

try:

try:

opts, args = getopt.getopt(argv[1:], "h", ["help"])

except getopt.error, msg:

raise Usage(msg)

# more code, unchanged

except Usage, err:

print >>sys.stderr, err.msg

print >>sys.stderr, "for help use --help"

return 2



if __name__ == "__main__":

sys.exit(main())









http://www.artima.com/weblogs/viewpost.jsp?thread=4829

Oops. I meant Guido van Rossum
 
W

Wanderer

Yes, but you've put the message in msg, and Exception doesn't have that



That's weird. I got this Exception class definition idea from this post by Guido van Rostrum, Where he gives this main function to look like



import sys

import getopt



class Usage(Exception):

def __init__(self, msg):

self.msg = msg



def main(argv=None):

if argv is None:

argv = sys.argv

try:

try:

opts, args = getopt.getopt(argv[1:], "h", ["help"])

except getopt.error, msg:

raise Usage(msg)

# more code, unchanged

except Usage, err:

print >>sys.stderr, err.msg

print >>sys.stderr, "for help use --help"

return 2



if __name__ == "__main__":

sys.exit(main())









http://www.artima.com/weblogs/viewpost.jsp?thread=4829

Oops. I meant Guido van Rossum
 
M

MRAB

Yes, but you've put the message in msg, and Exception doesn't have that

attribute.

That's weird. I got this Exception class definition idea from this post by Guido van Rostrum, Where he gives this main function to look like

import sys
import getopt

class Usage(Exception):
def __init__(self, msg):
self.msg = msg

def main(argv=None):
if argv is None:
argv = sys.argv
try:
try:
opts, args = getopt.getopt(argv[1:], "h", ["help"])
except getopt.error, msg:
raise Usage(msg)
# more code, unchanged
except Usage, err:
print >>sys.stderr, err.msg
print >>sys.stderr, "for help use --help"
return 2

if __name__ == "__main__":
sys.exit(main())




http://www.artima.com/weblogs/viewpost.jsp?thread=4829
Note how it explicitly prints err.msg.
 
W

Wanderer

That's weird. I got this Exception class definition idea from this post by Guido van Rostrum, Where he gives this main function to look like

import sys
import getopt

class Usage(Exception):
def __init__(self, msg):
self.msg = msg

def main(argv=None):
if argv is None:
argv = sys.argv

opts, args = getopt.getopt(argv[1:], "h", ["help"])
except getopt.error, msg:
raise Usage(msg)
# more code, unchanged
except Usage, err:
print >>sys.stderr, err.msg
print >>sys.stderr, "for help use --help"
return 2

if __name__ == "__main__":

Note how it explicitly prints err.msg.

Not in the raise statement.

Adding the def __str__ made it work for me.
Thanks
 
W

Wanderer

That's weird. I got this Exception class definition idea from this post by Guido van Rostrum, Where he gives this main function to look like

import sys
import getopt

class Usage(Exception):
def __init__(self, msg):
self.msg = msg

def main(argv=None):
if argv is None:
argv = sys.argv

opts, args = getopt.getopt(argv[1:], "h", ["help"])
except getopt.error, msg:
raise Usage(msg)
# more code, unchanged
except Usage, err:
print >>sys.stderr, err.msg
print >>sys.stderr, "for help use --help"
return 2

if __name__ == "__main__":

Note how it explicitly prints err.msg.

Not in the raise statement.

Adding the def __str__ made it work for me.
Thanks
 
T

Terry Reedy

Wouldn't PvCamError inherit __str__() from Exception?

Exception instances get a .args attibute set to the arguments of the
class call and printed in the .__str__ message.
['__cause__', '__class__', '__context__', '__delattr__', '__dict__',
'__dir__', '__doc__', '__eq__', '__format__', '__ge__',
'__getattribute__', '__gt__', '__hash__', '__init__', '__le__',
'__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__',
'__subclasshook__', '__suppress_context__', '__traceback__', 'args',
'with_traceback']Exception('abc', 1)

So class MyError(Exception) will get that basic default behavior. For
fancier printing, one needs a fancier .__str__ method ;-).
 
S

Steven D'Aprano

How do you get Exceptions to print messages? I have an exception defined
like this

class PvCamError(Exception):
def __init__(self, msg):
self.msg = msg

Please don't invent yet another interface for exception messages.
Exceptions already have two defined interfaces for accessing the error
message:

exception.message # older, now obsolete, and gone in Python 3.
exception.args # recommended way

Please use the same interface that nearly all exceptions already have and
use an "args" argument. The easiest way to do this is also the simplest:

class PvCamError(Exception): pass


If you *must* support "msg", do something like this:

class PvCamError(Exception):
def __init__(self, msg, *args):
super(PvCamError, self).__init__(msg, *args) # see footnote [1]
self.msg = msg





[1] If you're using Python 3, you can abbreviate the super call to:

super().__init__(self, msg, *args)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top