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 raiseE1raiseE1,E2
The first form is equivalent to “raise
None,None” and the second form is
equivalent to “raise ”. 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:
E1, None
| | Exception type | Exception value |
|---|---|---|---|
None | None |
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”.
| |
| class | None |
|
|
| class |
instance of
| | |
| class | tuple | |
|
| class | none of the above | |
|
| instance | None |
type(
|
|
The current recommended practice is to use a raise statement of this form:
raise E(...)
where is
some class derived from the built-in EException 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