当前位置: 首页 > 图灵资讯 > 行业资讯> python忽略异常的方法

python忽略异常的方法

发布时间:2024-08-21 22:19:20

1、try except

最常见的忽略异常的方法是使用句块try except,然后在语句 except 中只有 pass。

importcontextlib


classNonFatalError(Exception):
pass


defnon_idempotent_operation():
raiseNonFatalError(
'Theoperationfailedbecauseofexistingstate'
)


try:
print('tryingnon-idempotentoperation')
non_idempotent_operation()
print('succeeded!')
exceptNonFatalError:
pass

print('done')

#output
#tryingnon-idempotentoperation
#done

在这种情况下,操作失败并忽略了错误。

2、contextlib.suppress()

try:except 可替换 contextlib.suppress()更清楚地抑制类异常 with 块发生在任何地方。

importcontextlib


classNonFatalError(Exception):
pass


defnon_idempotent_operation():
raiseNonFatalError(
'Theoperationfailedbecauseofexistingstate'
)


withcontextlib.suppress(NonFatalError):
print('tryingnon-idempotentoperation')
non_idempotent_operation()
print('succeeded!')

print('done')

#output
#tryingnon-idempotentoperation
#done

以上是python忽略异常的两种方法,希望对大家有所帮助。更多Python学习指导:python基础教程

本文教程操作环境:windows7系统Python 3.9.1,DELL G3电脑。

相关文章

python3兼容python2吗

python3兼容python2吗

2025-05-09
python3 whl怎么安装

python3 whl怎么安装

2025-05-09
python 字典怎么提取value

python 字典怎么提取value

2025-05-09
python 怎样计算字符串的长度

python 怎样计算字符串的长度

2025-05-09
python 怎么样反向输出字符串

python 怎么样反向输出字符串

2025-05-09
python 怎么判断字符串开头

python 怎么判断字符串开头

2025-05-09