如果except子句中的类是同一类或其基类,则该子句与异常兼容(但不是相反的方式-列出派生类的except子句与基类不兼容)。例如,以下代码将按此顺序打印B,C,D:
>>> class C(B):
pass
>>> class D(C):
pass
>>> for cls in [B,C,D]:
try:
raise cls()
except D:
print("D")
except C:
print("C")
except B:
print("B")
B
C
D
发生异常时,它可能具有关联的值,也称为异常的参数。参数的存在和类型取决于异常类型。
except子句可以在异常名称后指定一个变量。变量绑定到带有存储在中的参数的异常实例 instance.args。为了方便起见,定义了异常实例, str()以便可以直接打印自变量而无需引用.args。人们也可以在引发异常之前先实例化异常,然后根据需要向其添加任何属性。
>>> try:
... raise Exception('spam', 'eggs')
... except Exception as inst:
... print(type(inst)) # the exception instance
... print(inst.args) # arguments stored in .args
... print(inst) # __str__ allows args to be printed directly,
... # but may be overridden in exception subclasses
... x, y = inst.args # unpack args
... print('x =', x)
... print('y =', y)
...
<class 'Exception'>
('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs
如果异常处理程序立即在try子句中发生,则异常处理程序不仅会处理异常,而且如果它们在try子句中被调用(甚至间接调用)的函数中发生,异常处理程序也不会处理异常。例如:
>>> def this_fails():
x = 1/0
>>> try:
this_fails()
except ZeroDivisionError as err:
print('Handling run-time error:',err)
Handling run-time error: division by zero
>>> raise NameError('HiThere')
Traceback (most recent call last):
File "" , line 1, in <module>
raise NameError('HiThere')
NameError: HiThere
>>> raise ValueError
Traceback (most recent call last):
File "" , line 1, in <module>
raise ValueError
ValueError
>>> try:
raise NameError('HiThere!')
except NameError:
print('An exception flew by!')
An exception flew by!
如果您需要确定是否引发了异常,但又不想处理该异常,则可以使用一种更简单的raise语句形式来重新引发该异常:
>>> try:
raise NameError('HiThere!')
except NameError:
print('An exception flew by!')
raise
An exception flew by!
Traceback (most recent call last):
File "" , line 2, in <module>
raise NameError('HiThere!')
NameError: HiThere!
try语句还有另一个可选子句,用于定义必须在所有情况下都必须执行的清理操作。
>>> try:
... raise KeyboardInterrupt
... finally:
... print('Goodbye, world!')
...
Goodbye, world!
KeyboardInterrupt
Traceback (most recent call last):
File "" , line 2, in <module>
如果该try子句中发生了异常且尚未由except子句处理 (或在exceptor else子句中发生),则finally在执行该子句后将重新引发该异常。
finally当try通过break,continue或return语句留下语句的 任何其他子句时,该子句也“跳出时”执行。
>>> def divide(x, y):
... try:
... result = x / y
... except ZeroDivisionError:
... print("division by zero!")
... else:
... print("result is", result)
... finally:
... print("executing finally clause")
...
>>> divide(2, 1)
result is 2.0
executing finally clause
>>> divide(2, 0)
division by zero!
executing finally clause
>>> divide("2", "1")
executing finally clause
Traceback (most recent call last):
File "" , line 1, in <module>
File "" , line 3, in divide
TypeError: unsupported operand type(s) for /: 'str' and 'str'
with open("myfile.txt") as f:
for line in f:
print(line, end="")
执行该语句后,即使处理行时遇到问题,文件f也始终关闭。像文件一样提供预定义清除操作的对象将在其文档中进行说明。
①https://docs.python.org/3.6/tutorial/errors.html?highlight=exceptions
②https://docs.python.org/3.6/reference/compound_stmts.html#except
③https://docs.python.org/3.6/library/exceptions.html
④https://docs.python.org/3.6/reference/simple_stmts.html#raise