python忽略异常的方法

Python (270) 2023-06-16 16:06:31

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忽略异常的两种方法,希望对大家有所帮助。

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

THE END

发表回复