异常链
如果一个未处理的异常发生在 except 部分内,它将会有被处理的异常附加到它上面,并包括在错误信息中:
>>>
try:
open("database.sqlite")
except OSError:
raise RuntimeError("unable to handle error")
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'database.sqlite'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
RuntimeError: unable to handle error
为了表明一个异常是另一个异常的直接后果, raise 语句允许一个可选的 from 子句:
# exc must be exception instance or None.
raise RuntimeError from exc
转换异常时,这种方式很有用。例如:
>>>
def func():
raise ConnectionError
try:
func()
except ConnectionError as exc:
raise RuntimeError('Failed to open database') from exc
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "<stdin>", line 2, in func
ConnectionError
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
RuntimeError: Failed to open database
它还允许使用 from None 表达禁用自动异常链:
>>>
try:
open('database.sqlite')
except OSError:
raise RuntimeError from None
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
RuntimeError
异常链机制详见 内置异常。
|