3.4.5 忽略异常
很多情况下,忽略库产生的异常通常很有用,因为这个错误可能会显示期望的状态已经被实现,否则该错误可以被忽略。要忽略异常,最常用的方法是利用一个try:except语句,其在except块中只包含一个pass语句。
import contextlib
class NonFatalError(Exception):
pass
def non_idempotent_operation():
raise NonFatalError(
'The operation failed because of existing state'
)
try:
print('trying non-idempotent operation')
non_idempotent_operation()
print('succeeded!')
except NonFatalError:
pass
print('done')
在这种情况下,这个操作会失败,而错误将被忽略。
运行结果:
trying non-idempotent operation
done
try:except也可以被替换为contextlib.suppress(),以更显式地抑制with块中产生某一类异常。
import contextlib
class NonFatalError(Exception):
pass
def non_idempotent_operation():
raise NonFatalError(
'The operation failed because of existing state'
)
with contextlib.suppress(NonFatalError):
print('trying non-idempotent operation')
non_idempotent_operation()
print('succeeded!')
print('done')
在这个更新后的版本中,异常会被完全丢弃。
运行结果:
trying non-idempotent operation
done