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

23.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 25, “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 23.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(...)

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 as x:
...     pass
... 
>>> type(x)
<type 'exceptions.ValueError'>
>>> x.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 VocationError(Exception):
...     def __init__(self, mismatch):
...         Exception.__init__(self, mismatch)
... 
>>> try:
...     print "And now, the Vocational Guidance Counsellor Sketch."
...     raise VocationError("Does not have proper hat")
...     print "This print statement will not be reached."
... except VocationError as problem:
...     print "Vocation problem: {0}".format(problem)
... 
And now, the Vocational Guidance Counsellor Sketch.
Vocation problem: Does not have proper hat