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 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 16.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:
raiseE(message)
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, 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.