e.g.
try:
foo()
bar()
except:
pass
When foo function raise an exception, how to skip to the next line (bar) and execute it?
Can't be done if the call to bar
is inside the try
-block. Either you have to put the call outside of the try-except block, or use the else
:
try:
foo()
except:
pass
else:
bar()
If bar
might throw an exception as well, you have to use a separate try
block for bar
.
If you have just two functions, foo() bar(), check the other solutions. If you need to run A LOT of 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]
If you want exceptions from both functions to be handled by the same except clause, then use an inner try/finally block:
try:
try:
foo()
finally:
bar()
except Exception:
print 'error'
If there is an exception in foo()
, first bar()
will be executed, then the except clause.
However, it's generally good practice to put the minimum amount of code inside a try block, so a separate exception handler for each function might be best.
That is not the intended way for try/except blocks to be used. If bar()
should be executed even if foo()
fails, you should put each in its own try/except block:
try:
foo()
except:
pass # or whatever
try:
bar()
except:
pass # or whatever
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.