8.4 抛出异常 Raising Exceptions

The raise statement allows the programmer to force a specified exception to occur. For example:

在发生了特定的异常时,程序员可以用 raise 语句强制抛出异常。例如:

>>> raise NameError, 'HiThere'
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: HiThere

The first argument to raise names the exception to be raised. The optional second argument specifies the exception's argument.

第一个参数指定了所抛出异常的名称,第二个指定了异常的参数。

If you need to determine whether an exception was raised but don't intend to handle it, a simpler form of the raise statement allows you to re-raise the exception:

如果你决定抛出一个异常而不处理它, raise 语句可以让你很简单的重新抛出该异常。

>>> try:
...     raise NameError, 'HiThere'
... except NameError:
...     print 'An exception flew by!'
...     raise
...
An exception flew by!
Traceback (most recent call last):
  File "<stdin>", line 2, in ?
NameError: HiThere