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?
Note however that it is considered a bad practice to have a bare
except
. You should catch for a specific exception instead. I captured forException
because that's as good as I can do without knowing what exceptions the methods might throw.I don't think you want to do this. The correct way to use a
try
statement in general is as precisely as possible. I think it would be better to do:You could iterate through your methods...
special_func to avoid try-except repetition:
Run code:
Output looks like:
To convert to variables:
Variables would look like:
one way you could handle this is with a generator. Instead of calling the function, yield it; then whatever is consuming the generator can send the result of calling it back into the generator, or a sentinel if the generator failed: The trampoline that accomplishes the above might look like so:
a generator that would be compatible with this would look like this:
Note that
do_many_things()
does not calldo_smth*
, it just yields them, andconsume_exceptions
calls them on its behalf'continue' is allowed within an 'except' or 'finally' only if the try block is in a loop. 'continue' will cause the next iteration of the loop to start.
So you can try put your two or more functions in a list and use loop to call your function.
Like this:
For full information you can go to this link