Python Ignore Exception and Go Back to Where I Was

Viewed 13469

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 do_something1, how to make the code ignore it and keep finishing do_something1 and process do_something2? My code just go to finally block after process pass in except block. Please advise, thanks.

try:
    do_something1
    do_something2
    do_something3
    do_something4
except Exception:
    pass
finally:
    clean_up

EDIT: Thanks for the reply. Now I know what's the correct way to do it. But here's another question, can I just ignore a specific exception (say if I know the error number). Is below code possible?

try:
    do_something1
except Exception.strerror == 10001:
    pass

try:
    do_something2
except Exception.strerror == 10002:
    pass
finally:
    clean_up

do_something3
do_something4
7 Answers

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
Related