e.g.
try:
foo()
bar()
except:
pass
When foo function raise an exception, how to skip to the next line (bar) and execute it?
Continue in Error Handling—Try, Except, Continue. If you need to handle exceptions in a loop, use the continue statement to skip the “rest of the loop”. print(" But I don't care! ") for number in [1, 2, 3]: try: print(x) except: print("Exception was thrown") print(" But I don't care!
If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then, if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try/except block.
Using Try Exceptexcept ... block to catch the ZeroDivisionError exception and ignore it. In the above code, we catch the ZeroDivisionError exception and use pass to ignore it. So, when this exception happens, nothing will be thrown and the program will just keep running by ignoring the zero number.
To avoid this, use the continue statement in the except block. This skips the rest of the loop when an exception occurs.
Take bar()
out of the try
block:
try:
foo()
except:
pass
bar()
Btw., watch out with catch-all except
clauses. Prefer to selectively catch the exceptions that you know you can handle/ignore.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With