Difference between revisions of "Exception Handling in Python"

From PeformIQ Upgrade
Jump to navigation Jump to search
(Created page with ' =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 ...')
 
Line 1: Line 1:




Line 15: Line 14:


  try:
  try:
    raise CustomException("My Useful Error Message")
    raise CustomException("`Useful Error Message")
  except CustomException, (instance):
  except CustomException, (instance):
    print "Caught: " + instance.parameter
    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 usually we just extend the list — rather than creating it:
 
try:
    self.items.extend(new_items)
except AttributeError:
    self.items = list(new_items)


[[category:Python]]
[[category:Python]]

Revision as of 22:44, 19 September 2011


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 usually we just extend the list — rather than creating it:

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