Defining a new exception with multiple args

Daniel Klein danielk at aracnet.com
Thu Jan 11 22:26:02 EST 2001


On Thu, 11 Jan 2001 11:50:40 -0500, "Steve Holden" <sholden at holdenweb.com>
wrote:

[snip]
>> Why is it showing '<unprintable instance object>' instead of the arguments passed?
>>
>Because it can't print instance objects?
>
>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?

Immensely!!! As I understand it now, the act of catching the exception (_not_
raising it) is what  instantiates an exception  object, to which you can then
access the instance fields, just like any other class.

So far so good.

The only part that remains unclear is that I can define an exception as

class MyException:
	pass

>>> raise MyException, 'foo'
Traceback (innermost last):
  File "<pyshell#13>", line 1, in ?
    raise MyException, 'foo'
MyException: foo

and everything comes out as expected. I would have thought that you would have
to enclose this in a try/except just like the multi-argument class. Apparently,
Python provides some default behavior for simple exceptions.

If anyone would like to explain further, I think this would benefit all of us
who are new to Python and OOP.

Thanks again Steve, you nailed this one!

Daniel Klein



More information about the Python-list mailing list