6.3 The raise Statement

You can use the raise statement to raise an exception explicitly. raise is a simple statement with the following syntax:

raise [expression1[, expression2]]

Only an exception handler (or a function that a handler calls, directly or indirectly) can use raise without any expressions. A plain raise statement reraises the same exception object that the handler received. The handler terminates, and the exception propagation mechanism keeps searching for other applicable handlers. Using a raise without expressions is useful when a handler discovers that it is unable to handle an exception it receives, so the exception should keep propagating.

When only expression1 is present, it can be an instance object or a class object. In this case, if expression1 is an instance object, Python raises that instance. When expression1 is a class object, raise instantiates the class without arguments and raises the resulting instance. When both expressions are present, expression1 must be a class object. raise instantiates the class, with expression2 as the argument (or multiple arguments if expression2 is a tuple), and raises the resulting instance.

Here's an example of a typical use of the raise statement:

def crossProduct(seq1, seq2):
    if not seq1 or not seq2:
        raise ValueError, "Sequence arguments must be non-empty"
    return [ (x1, x2) for x1 in seq1 for x2 in seq2 ]

The crossProduct function returns a list of all pairs with one item from each of its sequence arguments, but first it tests both arguments. If either argument is empty, the function raises ValueError, rather than just returning an empty list as the list comprehension would normally do. Note that there is no need for crossProduct to test if seq1 and seq2 are iterable: if either isn't, the list comprehension itself will raise the appropriate exception, presumably a TypeError. Once an exception is raised, be it by Python itself or with an explicit raise statement in your code, it's up to the caller to either handle it (with a suitable try/except statement) or let it propagate further up the call stack.

Use the raise statement only to raise additional exceptions for cases that would normally be okay but your specifications define to be errors. Do not use raise to duplicate the error checking and diagnostics Python already and implicitly does on your behalf.

    Part III: Python Library and Extension Modules