第三章:算法-contextlib:上下文管理器工具-忽略异常

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值