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 ...

Get Python in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.