引发和处理异常情况

这是 Python 2 语法,请注意 raiseexcept 行上的逗号 ,

Python 2.x >= 2.3

try:
    raise IOError, "input/output error"
except IOError, exc:
    print exc

在 Python 3 中,删除了 , 语法,并用括号和 as 关键字替换:

try:
    raise IOError("input/output error")
except IOError as exc:
    print(exc)

为了向后兼容,Python 3 语法也可以在 Python 2.6 以后使用,因此它应该用于所有不需要与以前版本兼容的新代码。

Python 3.x >= 3.0

Python 3 还添加了异常链接 ,其中你可以发信号通知其他异常是导致此异常的原因。例如

try:
    file = open('database.db')
except FileNotFoundError as e:
    raise DatabaseError('Cannot open {}') from e

except 语句中引发的异常是 DatabaseError 类型,但原始异常标记为该异常的 __cause__ 属性。显示回溯时,原始异常也将显示在回溯中:

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
FileNotFoundError

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
DatabaseError('Cannot open database.db')

如果你在没有明确链接的情况下投入 except 块 :

try:
    file = open('database.db')
except FileNotFoundError as e:
    raise DatabaseError('Cannot open {}')

追溯是

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
FileNotFoundError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
DatabaseError('Cannot open database.db')

Python 2.x >= 2.0

Python 2.x 中都不支持任何一个; 如果在 except 块中引发另一个异常,则原始异常及其回溯将丢失。以下代码可用于兼容性:

import sys
import traceback

try:
    funcWithError()
except:
    sys_vers = getattr(sys, 'version_info', (0,))
    if sys_vers < (3, 0):
        traceback.print_exc()
    raise Exception("new exception")

Python 3.x >= 3.3

忘记之前抛出的异常,请使用 raise from None

try:
    file = open('database.db')
except FileNotFoundError as e:
    raise DatabaseError('Cannot open {}') from None

现在回溯就是这样

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
DatabaseError('Cannot open database.db')

或者为了使它与 Python 2 和 3 兼容,你可以像这样使用六个包:

import six
try:
    file = open('database.db')
except FileNotFoundError as e:
    six.raise_from(DatabaseError('Cannot open {}'), None)