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电脑。
