知行编程网知行编程网  2022-10-03 12:30 知行编程网 隐藏边栏  196 
文章评分 0 次,平均分 0.0
导语: 本文主要介绍了关于python忽略异常的方法的相关知识,包括python异常处理try,以及python错误类型异常这些编程知识,希望对大家有参考作用。

如何忽略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电脑。

本文为原创文章,版权归所有,欢迎分享本文,转载请保留出处!

知行编程网
知行编程网 关注:1    粉丝:1
这个人很懒,什么都没写
扫一扫二维码分享