Aug 3, 2012

Attaching custom exceptions to functions and classes

http://pydanny.com/attaching-custom-exceptions-to-functions-and-classes.html

class DoesNotCompute(Exception):
    """ Easy to understand naming conventions work best! """
    pass

def this_function(x):
    """ This function only works on numbers."""
    try:
        return x ** x
    except TypeError:
        raise DoesNotCompute

# Assign DoesNotCompute exception to this_function
this_function.DoesNotCompute = DoesNotCompute
>>> try:
...     this_function('is an example')
... except this_function.DoesNotCompute:
...     print('See what attaching custom exceptions to functions can do?')
...
...
See what attaching custom exceptions to functions can do?

No comments: