Difference between revisions of "Exception Handling in Python"
Jump to navigation
Jump to search
PeterHarding (talk | contribs) |
PeterHarding (talk | contribs) |
||
Line 1: | Line 1: | ||
=Custom Exceptions= | =Custom Exceptions= | ||
Line 42: | Line 41: | ||
self.items = list(new_items) | self.items = list(new_items) | ||
Using exceptions, you can emphasize the normal program flow — that | Using exceptions, you can emphasize the normal program flow — that you extend the list — rather than creating it: | ||
try: | try: |
Revision as of 23: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 you extend the list — rather than creating it:
try: self.items.extend(new_items) except AttributeError: self.items = list(new_items)