Next / Previous / Contents / TCC Help System / NM Tech homepage

16.6. The raise statement: Cause an exception

Python's exception mechanism is the universal framework for dealing with errors—situations where your program can't really proceed normally. For an overview, see Section 18, “Exceptions: Error signaling and handling”.

There are three forms of the raise statement:

raise
raise E1
raise E1, E2

The first form is equivalent to “raise None,None” and the second form is equivalent to “raise E1, None”. Each form raises an exception of a given type and with a given value. The type and value depend on how many expressions you provide:

E1E2Exception typeException value
NoneNone Re-raise the current exception, if any. This might be done, for example, inside an except, else, or finally block; see Section 16.8, “The try statement: Anticipate exceptions”.
classNone E1 E1()
class instance of E1 E1E2
classtupleE1 E1(*E2)
classnone of the aboveE1 E1(E2)
instanceNone type(E1) E1

The current recommended practice is to use a raise statement of this form:

raise E(message)

where E is some class derived from the built-in Exception class: you can use one of the built-in exceptions, or you can create your own exception classes.

For classes derived from Exception, the constructor takes one argument, an error message—that is, a string explaining why the exception was raised. The resulting instance makes that message available as an attribute named .message. Example:

>>> try:
...     raise ValueError('The day is too frabjous.')
... except ValueError, detail:
...     pass
... 
>>> type(detail)
<type 'exceptions.ValueError'>
>>> detail.message
'The day is too frabjous.'

To create your own exceptions, write a class that inherits from Exception and passes its argument to the parent constructor, as in this example.

>>> class FashionError(Exception):
...     def __init__(self, sin):
...         Exception.__init__(self, sin)
... 
>>> try:
...     print "Let's try shirt 14 and trouser 92."
...     raise FashionError('Clashing plaids.')
...     print "Hey, we got away with it!"
... except FashionError, problem:
...     print "Terminal fashion sin:", problem.message
... 
Let's try shirt 14 and trouser 92.
Terminal fashion sin: Clashing plaids.