导语:
本文主要介绍了关于python忽略异常的方法的相关知识,包括python异常处理try,以及python错误类型异常这些编程知识,希望对大家有参考作用。
1、try except
忽略异常的最常见方法是使用语句块 try except,然后传入语句 except。
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')
# output
# trying non-idempotent operation
# done
在这种情况下,操作失败并忽略错误。
2、contextlib.suppress()
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')
# output
# trying non-idempotent operation
# done
本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。
本文为原创文章,版权归知行编程网所有,欢迎分享本文,转载请保留出处!
你可能也喜欢
- ♥ python代码存储在哪里08/30
- ♥ 或者如何用python表达09/03
- ♥ python中如何判断是否是字符10/29
- ♥ 了解搭建selenium安装配置环境12/13
- ♥ anaconda中的python环境路径在哪里?08/12
- ♥ 如何计算python列表中元素的频率?10/05
内容反馈