Defining a new exception with multiple args

Steve Holden sholden at holdenweb.com
Thu Jan 11 11:50:40 EST 2001


"Daniel Klein" <danielk at aracnet.com> wrote in message
news:gnir5t80r7asgcp36jtssum2mspk5i5h4d at 4ax.com...
> 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
>
Perfectly sound exception definition. However, some defaults would not be
bad:

class RecordNotFoundException(Exception):
    def __init__(self, filename="Unknown file", recordid="unknown"):
        self.filename = filename
        self.recordid = recordid

> 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>
>
Well, what's wrong with this? You asked the interpreter to raise an
exception, it raised it, trapped it (as no handler was established by a
suitable try ... except) and reported on it.

> >>> raise RecordNotFoundException, ("myfile", "myid")
>
> produces the same result.

>
> I also tried defining the exception with
>
> import exception
> class RecordNotFoundException(exception.Exception):
>
> Why is it showing '<unprintable instance object>' instead of the arguments
I
> passed?
>
Because it can't print instance objects?

> Thanks for any assistence,
> Daniel Klein
>
Instead of just raising the exception, raise it in a way which allows you to
trap it. In a try ... except, the except can take just an exception (or, I
believe, a tuple of acceptable exceptions) or it can also take a name, which
will be bound to the exception raised. You can then use this name to access
the exception object and get at its insides:

>>> try:
...  raise RecordNotFoundException, ("file", "record")
... except RecordNotFoundException, x:
...  print "File:", x.filename, "record:", x.recordid
...
File: file record: record
>>> try:
...  raise RecordNotFoundException("file", "record")
... except RecordNotFoundException, x:
...  print "File:", x.filename, "record:", x.recordid
...
File: file record: record

Does this help?

regards
 Steve






More information about the Python-list mailing list