Our Exception Standards -- What do you think?

Doug Fort dougfort at downright.com
Sat Jan 27 20:48:46 EST 2001


This is a proposed standard I'm going to send to our development  team.
Even though I've been writing Python for a  while, I've found exception
handling obscure.  (I come from C, C++ and Java, where it's even more
obscure).  Here is what I've worked out for our team.  It might be of some
use to others, or perhaps you serious wizards can propose something better.

***

I have been working on putting out meaningful error messages.  A good part
of this is presenting Python exceptions in a readable way.  After some
struggle, I have a pattern that I think  will work for us.

The Library Manual recommends deriving all exceptions from the system
Exception class.  This class has a member called 'args' which is a tuple of
the arguments presented in its constructor.  The default __str__ operator
simply returns the args tuple as a string.
  class TestException(Exception):
      pass

  try:
      raise TestException("aaa", "bbb")
  catch TestException, instance:
      print instance

  ('aaa', 'bbb')
I propose that we follow this standard, with the enhancement of overloading
the  __str__ operator of individual exception classes.  For example, in the
specific case I am working on, we want all producer exceptions to include
the field name:
  class ProducerException(Exception):
      def __str__(self):
          if len(self.args) == 2:
              return "Field %s: %s" % (args[0], args[1])
          return str(args)

  class CurrentValueProducerException(...ProducerException):
      pass

  try:
      raise CurrentValueProducerException(self._fieldname, "No Data")
  except:
      exc_type, exc_value, exc_traceback = sys.exc_info()
      print "%s %s" % (string.split(str(exc_type), ".")[-1], str(exc_value))

  'CurrentValueProducerException Field email: No Data'
--
Doug Fort
Senior Meat Manager
Downright Software LLC
http://www.dougfort.net






More information about the Python-list mailing list