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 re-raises the same exception object that the handler received. The handler terminates, and the exception propagation mechanism keeps searching for other applicable handlers. Using raise
without expressions is useful when a handler discovers that it is unable to handle an exception it receives, or can handle the exception only partially, so the exception should keep propagating to allow handlers up the call stack to perform handling and clean-up.
When only expression1
is present, it can be a legacy-style instance object or class object (Python 2.5 changes this rule in order to allow new-style classes, as long as they inherit from the new built-in new-style class BaseException
and instances of BaseException
). 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 legacy-style class object. raise
instantiates the class, with expression2
as the argument (or multiple arguments if expression2
is a tuple), and raises the resulting instance. Note that the raise
statement is ...
Get Python in a Nutshell, 2nd Edition 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.