• 技术文章 >Python技术 >Python基础教程

    python忽略异常的方法

    小妮浅浅小妮浅浅2021-05-31 09:37:58原创8587

    1、try except

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

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    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 块的任何地方发生。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    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学习指路:python基础教程

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

    专题推荐:python忽略异常
    上一篇:python中contextmanager()的转换 下一篇:python os.path如何解析路径

    相关文章推荐

    • python新式类是什么• python响应头部是什么• python请求头如何自定义?• python如何使用requests检查请求• python中contextmanager()的转换

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网