Can I return to executing try-block after exception occurs? (The goal is to write less) For Example:
try:
do_smth1()
except:
pass
try:
do_smth2()
except:
pass
vs
try:
do_smth1()
do_smth2()
except:
??? # magic word to proceed to do_smth2() if there was exception in do_smth1
You can achieve what you want, but with a different syntax. You can use a "finally" block after the try/except. Doing this way, python will execute the block of code regardless the exception was thrown, or not.
Like this:
But, if you want to execute do_smth2() only if the exception was not thrown, use a "else" block:
You can mix them too, in a try/except/else/finally clause. Have fun!
Depending on where and how often you need to do this, you could also write a function that does it for you:
But as other answers have noted, having a null
except
is generally a sign something else is wrong with your code.While the other answers and the accepted one are correct and should be followed in real code, just for completeness and humor, you can try the
fuckitpy
( https://github.com/ajalt/fuckitpy ) module.Your code can be changed to the following:
Then calling
myfunc()
would calldo_smth2()
even if there is an exception indo_smth1())
Note: Please do not try it in any real code, it is blasphemy