Python Ignore Exception and Go Back to Where I Was

后端 未结 7 1318
孤街浪徒
孤街浪徒 2021-02-13 12:47

I know using below code to ignore a certain exception, but how to let the code go back to where it got exception and keep executing? Say if the exception \'Exception\' raises in

7条回答
  •  有刺的猬
    2021-02-13 13:28

    Python 3.4 added contextlib.suppress(), a context manager that takes a list of exceptions and suppresses them within the context:

    with contextlib.suppress(IOError):
      print('inside')
      print(pathlib.Path('myfile').read_text()) # Boom
      print('inside end')
    
    print('outside')
    

    Note that, just as with regular try/except, an exception within the context causes the rest of the context to be skipped. So, if an exception happens in the line commented with Boom, the output will be:

    inside
    outside
    

提交回复
热议问题