Python Ignore Exception and Go Back to Where I Was

2020-06-09 06:28发布

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条回答
手持菜刀,她持情操
2楼-- · 2020-06-09 06:51

This is pretty much missing the point of exceptions.

If the first statement has thrown an exception, the system is in an indeterminate state and you have to treat the following statement as unsafe to run.

If you know which statements might fail, and how they might fail, then you can use exception handling to specifically clean up the problems which might occur with a particular block of statements before moving on to the next section.

So, the only real answer is to handle exceptions around each set of statements that you want to treat as atomic

查看更多
登录 后发表回答