I have a loop that I want to terminate on KeyboardInterrupt:
while True:
try:
do_stuff()
except KeyboardInterrupt:
cleanup()
break
except Exception as e:
cleanup()
raise e
This works fine, but the dual cleanup() seems very unclean to me. I don’t like duplicated code. I tried using a context manager instead, but that introduced a lot of unnecessary complexity and nearly doubled the file size.
Is there a cleaner way to express my intent?
The
finallykeyword is exactly what you are looking for. The doc on errors and exceptions explains its usage.If the cleanup is only supposed to occur when leaving the loop, I suggest swapping the loop and the try :