How to continue the next line in a try block in Python?

eg.

try: foo() bar() except: pass 

When the foo function throws an exception, how do I go to the next line (line) and execute it?

+4
source share
5 answers

Take bar() from the try block:

 try: foo() except: pass bar() 

Btw., Be careful with general except . Prefer to selectively catch exceptions that, as you know, you can handle / ignore.

+8
source

It cannot be executed if the bar call is inside the try block. Either you must place the call outside the try-except block, or use else :

 try: foo() except: pass else: bar() 

If bar can throw an exception, you should use a separate try block for bar .

+5
source

This is not the intended way to use try / except blocks. If bar() should execute, even if foo() fails, you should put them in your own try / except block:

 try: foo() except: pass # or whatever try: bar() except: pass # or whatever 
+2
source

If you want exceptions from both functions to be handled by the same except clause, use the try / finally inner block:

 try: try: foo() finally: bar() except Exception: print 'error' 

If there is an exception in foo() , the first bar() will be executed, and then the except clause.

However, as a rule, it is good practice to put a minimal amount of code inside the try block, so there may be a better exception handler for each function.

0
source

If you have only two functions, foo () bar (), check out the other solutions. If you need to run many lines, try something like this example:

 def foo(): raise Exception('foo_message') def bar(): print'bar is ok' def foobar(): raise Exception('foobar_message') functions_to_run = [ foo, bar, foobar, ] for f in functions_to_run: try: f() except Exception as e: print '[Warning] in [{}]: [{}]'.format(f.__name__,e) 

Result:

 [Warning] in [foo]: [foo_message] bar is ok [Warning] in [foobar]: [foobar_message] 
0
source

All Articles