当前位置: 首页 > 图灵资讯 > 行业资讯> 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电脑。

相关文章

如何让vim支持python3

如何让vim支持python3

2025-09-12
python2.7和3.6区别有哪些

python2.7和3.6区别有哪些

2025-09-12
python3有serial库吗

python3有serial库吗

2025-09-12
python中w、r表示什么意思

python中w、r表示什么意思

2025-09-12
python中如何把list变成字符串

python中如何把list变成字符串

2025-09-12
python命名空间是什么

python命名空间是什么

2025-09-12