Edward Fu
Edward Fu

Reputation: 137

python ignore whichever line that causes error and continue running the code after that line

I understand the try/except method. What I'm trying to do is:

try:
    some_func1() #potentially raises error too
    do_something_else() #error was raised
    continue_doing_something_else() #continues here after handling error
except:
    pass

In the above code, when the error is raised at do_something_else(), the error is handled but then the try statement is exited.

What I want is for python to continue whatever code that is after the line that causes the error. Assuming that an error can happen anywhere in the try statement so I can't just wrap the try/except around do_something_else() itself, is there a way to do this in python?

Upvotes: 0

Views: 2489

Answers (2)

Baldrickk
Baldrickk

Reputation: 4409

Just put the code that you want to do after the possible exception after the except. You may want to use finally (see https://docs.python.org/3/tutorial/errors.html for the documentation):

try:
    some_func1()
    do_something_else() #error was raised
except:
    handle_exception()
finally:
    continue_doing_something_else() #continues here after handling error or if no error occurs

if continue_doing_something_else() can also throw exceptions, then put that in a try/except too:

try:
    some_func1()
    do_something_else() #error was raised
except:
    handle_exception1()
try:
    continue_doing_something_else()
except:
    handle_exception2()
finally:
    any_cleanup()

as a general rule, your exception handling should be kept as small in scope as possible while remaining sensible, consider excepting only the 'expected' exceptions and not all of them (e.g. except OSError: when attempting to open files)

Upvotes: 1

thebjorn
thebjorn

Reputation: 27321

What you want to do (try with restart) is not possible in Python. Lisp can do it (http://www.gigamonkeys.com/book/beyond-exception-handling-conditions-and-restarts.html), and you can implement it in Scheme using call/cc.

Upvotes: 1

Related Questions