How to properly ignore exceptions

前端 未结 11 2251
粉色の甜心
粉色の甜心 2020-11-22 02:18

When you just want to do a try-except without handling the exception, how do you do it in Python?

Is the following the right way to do it?

try:
    s         


        
11条回答
  •  萌比男神i
    2020-11-22 03:08

    First I quote the answer of Jack o'Connor from this thread. The referenced thread got closed so I write here:

    "There's a new way to do this coming in Python 3.4:

    from contextlib import suppress
    
    with suppress(Exception):
        # your code
    

    Here's the commit that added it: http://hg.python.org/cpython/rev/406b47c64480

    And here's the author, Raymond Hettinger, talking about this and all sorts of other Python hotness: https://youtu.be/OSGv2VnC0go?t=43m23s

    My addition to this is the Python 2.7 equivalent:

    from contextlib import contextmanager
    
    @contextmanager
    def ignored(*exceptions):
        try:
            yield
        except exceptions:
            pass
    

    Then you use it like in Python 3.4:

    with ignored(Exception):
        # your code
    

提交回复
热议问题