I would like to execute a loop that attempts to run a block of code, and skips past any iterations that happen to fail. However I would also like to be able to pass in a debug flag, so that if one of the iterations fails the program crashes and the user can see the backtrace to help themselves see where it failed. Essentially, I want to do this:
debug = False # or True
for i in range(10):
if not debug:
try:
# many lines of code
except:
print(f'Case {i} failed')
else:
# many lines of code
However, I don't want to duplicate the #many lines of code
. I could wrap them in a helper function and do precisely the structure I wrote above, but I'm going to have to pass around a bunch of variables that will add some complexity (aka unit tests that I don't want to write). Is there another way to do this?
Best solution shy of factoring out many lines of code
to its own function (which is often a good idea, but not always) would be to unconditionally use the try
/ except
, but have the except
conditionally re-raise the exception:
debug = False # or True
for i in range(10):
try:
# many lines of code
except:
if debug:
raise # Bare raise reraises the exception as if it was never caught
print(f'Case {i} failed')
A caught exception reraised with a bare raise
leaves no user-visible traces to distinguish it from an uncaught exception; the traceback is unchanged, with no indication of it passing through the except
block, so the net effect is identical to your original code, aside from debug
being evaluated later (not at all if no exception occurs) and many lines of code
appearing only once.
Side-note: Bare except
blocks are a bad idea. If nothing else, limit it to except Exception:
so you're not catching and suppressing stuff like KeyboardInterrupt
or SystemExit
when not in debug mode.
Best way is to use a function, just one line more does not matter too much.
Otherwise, if there is no need to test debug
, There is no need to repeat the else
block. Because if statements in try
don't raise error, then the it will execute and result will be shown normally.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.