You want that if any of the doSomething1
, doSomething2
and doSomething3
method fails, then the try
block is skipped, and the doSomething4
method is run.
Well, it's not logically possible. If doSomething1
fails, then it has been executed, hence the whole try
can no more be entirely skipped. Same for doSomething2
: if it fails, then it has been run, and doSomething1
did not failed, so only doSomething3
can still be skipped.
Here are a few different behaviours you can implement.
Behaviour 1
try:
doSomething1()
doSomething2()
doSomething3()
except:
doSomething4()
Tries to run doSomething1
, doSomething2
and doSomething3
. If one of them fails, the following ones are skipped, and doSomething4
is executed. Else, doSomething4
is skipped.
Behaviour 2
try:
doSomething1()
doSomething2()
doSomething3()
finally:
doSomething4()
Tries to run doSomething1
, doSomething2
and doSomething3
. If one of them fails, the following ones are skipped. In any case, doSomething4
is executed at the end.
Behaviour 3
try:
doSomething1()
except:
try:
doSomething2()
except:
pass
else:
try:
doSomething3()
except:
pass
else:
doSomething4()
else:
try:
doSomething2()
except:
try:
doSomething3()
except:
pass
else:
doSomething4()
else:
try:
doSomething3()
except:
doSomething4()
If exactly one of doSomething1
, doSomething2
and doSomething3
fails, doSomething4
is run. This behaviour could be implemented in a much easier way with neater exception management, but this code has the merit of using only try
s, except
s and else
s.
Behaviour 4
try:
doSomething1()
doSomething2()
doSomething3()
doSomething4()
except:
...
This is what corresponds to the title of your question. If none of doSomething1
, doSomething2
and doSomething3
fails, doSomething4
is run; else, it is not run.