Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Ignore Exception and Go Back to Where I Was

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
like image 449
Stan Avatar asked Sep 28 '10 23:09

Stan


2 Answers

There's no direct way for the code to go back inside the try-except block. If, however, you're looking at trying to execute these different independant actions and keep executing when one fails (without copy/pasting the try/except block), you're going to have to write something like this:

actions = (
    do_something1, do_something2, #...
    )
for action in actions:
    try:
        action()
    except Exception, error:
        pass
like image 142
André Caron Avatar answered Nov 07 '22 19:11

André Caron


update. The way to ignore specific exceptions is to catch the type of exception that you want, test it to see if you want to ignore it and re-raise it if you dont.

try:
    do_something1
except TheExceptionTypeThatICanHandleError, e:
    if e.strerror != 10001:
        raise
finally:
     clean_up

Note also, that each try statement needs its own finally clause if you want it to have one. It wont 'attach itself' to the previous try statement. A raise statement with nothing else is the correct way to re-raise the last exception. Don't let anybody tell you otherwise.


What you want are continuations which python doesn't natively provide. Beyond that, the answer to your question depends on exactly what you want to do. If you want do_something1 to continue regardless of exceptions, then it would have to catch the exceptions and ignore them itself.

if you just want do_something2 to happen regardless of if do_something1 completes, you need a separate try statement for each one.

try:
   do_something1()
except:
   pass

try:
   do_something2()
except:
   pass

etc. If you can provide a more detailed example of what it is that you want to do, then there is a good chance that myself or someone smarter than myself can either help you or (more likely) talk you out of it and suggest a more reasonable alternative.

like image 31
aaronasterling Avatar answered Nov 07 '22 19:11

aaronasterling