python catch exception and continue try block
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
No, you cannot do that. That's just the way Python has its syntax. Once you exit a try-block because of an exception, there is no way back in.
What about a for-loop though?
funcs = do_smth1, do_smth2
for func in funcs:
try:
func()
except Exception:
pass # or you could use 'continue'
Note however that it is considered a bad practice to have a bare except
. You should catch for a specific exception instead. I captured for Exception
because that's as good as I can do without knowing what exceptions the methods might throw.
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:
@fuckitpy
def myfunc():
do_smth1()
do_smth2()
Then calling myfunc()
would call do_smth2()
even if there is an exception in do_smth1())
Note: Please do not try it in any real code, it is blasphemy