Exception Handling in Python

From PeformIQ Upgrade
Revision as of 23:45, 19 September 2011 by PeterHarding (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

A good reference - http://en.wikibooks.org/wiki/Python_Programming/Exceptions

Custom Exceptions

Code similar to that seen above can be used to create custom exceptions and pass information along with them. This can be extremely useful when trying to debug complicated projects. Here is how that code would look; first creating the custom exception class:

  class CustomException(Exception):
      def __init__(self, value):
          self.parameter = value
      def __str__(self):
          return repr(self.parameter)

And then using that exception:

try:
   raise CustomException("`Useful Error Message")
except CustomException, (instance):
   print "Caught: " + instance.parameter
   Python 2.5

Try/Except/Else/Finally

Python versions 2.5 and later allow:

try:
   result = x / z
except ZeroDivisionError:
   print "division by zero!"
else:
   print "result is", result
finally:
   print "executing finally clause"

More Exotic Examples

Say you want to add items to a list but don't want to use "if" statements to initialize the list - so replace this:

if hasattr(self, 'items'):
   self.items.extend(new_items)
else:
   self.items = list(new_items)

Using exceptions, you can emphasize the normal program flow — that you extend the list — rather than creating it:

try:
   self.items.extend(new_items)
except AttributeError:
   self.items = list(new_items)

Built In Exceptions

See here...