Defining a new exception with multiple args

D-Man dsh8290 at rit.edu
Thu Jan 11 12:23:36 EST 2001


On Thu, Jan 11, 2001 at 07:14:25AM -0800, Daniel Klein wrote:
| Using the Beazley book as a guide, I have defined a new exception as:
| 
| class RecordNotFoundException(Exception):
|     def __init__(self, filename, recordid):
|         self.filename = filename
|         self.recordid = recordid
| 

Here you have set some instance variables that only exist in your
class.

| However, this is what happens when I raise this exception:
| 
| >>> raise RecordNotFoundException("myfile", "myid")
| Traceback (innermost last):
|   File "<pyshell#40>", line 1, in ?
|     raise RecordNotFoundException("myfile", "myid")
| RecordNotFoundException: <unprintable instance object>

Here the interpreter has the exception instance, but the print
routine doesn't know about your special arguments.

 
| Why is it showing '<unprintable instance object>' instead of the arguments I
| passed?
| 
| Thanks for any assistence,
| Daniel Klein

try this:

class MyExcept( Exception ) :
	def __init__( self , *args ) :
		# init the Exception's members
		Exception.__init__( self , args )

raise MyExcept( "hello" )
raise MyExcept( "hello" , "another arg" )

# You can even type this without any error (that is, other than the one
# you are explicitly creating ;-))

raise Exception( "first arg" , "second arg" , "etc" )


And you will see the arguments printed.  The *args argument is a
tuple, so when the exception is printed, you will have the arguments
wrapped in ()'s.  Check the documentation on exceptions,  there is
probably (at least I hope so) an function you can define that will
handle custom printing of custom Exceptions.

HTH,
-D





More information about the Python-list mailing list