Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to continue with next line in a Python's try block?

e.g.

try:
    foo()
    bar()
except: 
    pass

When foo function raise an exception, how to skip to the next line (bar) and execute it?

like image 585
Howard Avatar asked Oct 31 '11 11:10

Howard


People also ask

How do you do continue in try and except in Python?

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!

Does code continue after Except Python?

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.

How do you skip a try block in Python?

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.

Can you use continue in except?

To avoid this, use the continue statement in the except block. This skips the rest of the loop when an exception occurs.


1 Answers

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.

like image 184
Fred Foo Avatar answered Oct 02 '22 02:10

Fred Foo