您好,欢迎来到要发发知识网。
搜索
您的当前位置:首页python忽略异常的方法

python忽略异常的方法

来源:要发发知识网

1、try except

忽略异常的最常见方法是使用语句块try except,然后在语句 except 中只有 pass。

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

以上就是python忽略异常的两种方法,希望对大家有所帮助。更多Python学习指路:

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

Copyright © 2019- net188.cn 版权所有 湘ICP备2022005869号-2

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务