Defining a new exception with multiple args

Randall Kern randy at spoke.net
Thu Jan 11 15:01:39 EST 2001


You could also override __str__:

class RecordNotFoundException(Exception):
    def __init__(self, filename, recordid):
        self.filename = filename
        self.recordid = recordid

    def __str__(self):
        return '%s(%s)' % (self.filename, self.recordid)

This will show a more interesting msg when you raise the error:
>>> raise RecordNotFoundException('foo.db', 5)
Traceback (innermost last):
  File "<stdin>", line 1, in ?
__main__.RecordNotFoundException: foo.db(5)


-Randy

"D-Man" <dsh8290 at rit.edu> wrote in message
news:mailman.979233912.12772.python-list at python.org...
> 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