How robust is Python ?

Steve Holden sholden at holdenweb.com
Fri Jan 12 13:50:24 EST 2001


In the example you give, the "print" statement is a part of the class
definition suite. It will therefore be executed when the class definition is
processed:

>>> class newclass:
...  print "Something"
...
Something

This feature can be used to assign class variables (shared across all
instances), because the class namespace is local at time the definition
suite is processed.

If you wanted to print something when the exception was raised, you could
put the print statement in the __init__ method of the class: when an
exception is rasied, an instance is created:

>>> class WeirdException:
...  def __init__(self):
...   print "Weird stuff, man"
...
>>> raise WeirdException
Weird stuff, man
Traceback (innermost last):
  File "<interactive input>", line 1, in ?
WeirdException: <__main__.WeirdException instance at 016EC35C>

You can, of course, use *instances* of your exception class rather than the
class itself to raise exceptions.  You can either do this by simply using an
instance call directly, or you can add a single argument or a tuple (which
will become the argument list) to the "raise" statement:

>>> class ParamException:
...  def __init__(self, file="Unknown", line="not given"):
...   self.file = file
...   self.line = line
...
This allows you to pick up the exception and handle it using its methods and
attributes. This example doesn't use any methods, just attributes, but it
should give you the idea.
>>> try:
...  raise ParamException("BigFile.txt", 23)
... except ParamException, p:
...  print "Except: error in file", p.file, "at line", p.line
...
Except: error in file BigFile.txt at line 23

Sorry about the tabbing in this mail.

regards
 Steve


----- Original Message -----
From: "Sandipan Gangopadhyay" <sandipan at vsnl.com>
To: "Steve Holden" <sholden at holdenweb.com>
Sent: Friday, January 12, 2001 1:27 PM
Subject: Re: How robust is Python ?


> Absolutely. Its superfluous to catch AnyOldNameILike separately if I
intend
> to do nothing different about it !
>
> I would however, prefer your suggestion of creating a special exception
than
> to (ab)use an existing one. Just doesnt seem right.
>
> I am curious about something, though. What would happen if I replaced pass
> in -
>
> class AnyOldNameILike:
>     print "Hi there"
>
> Ie, if/when is this print executed ?
>
> My thanks and regards,
>
> Sandipan
>






More information about the Python-list mailing list