An inescapable while loop in Python
fman is programmed in Python. While hunting a bug today, I realised I've been making a mistake for the past 6 years. Consider the following code:
from time import sleep
while True:
try:
sleep(.1)
except:
pass
What do you think happens when you press Ctrl+C? I would have
expected to get out of the infinite loop. But it doesn't work! You have
to press Ctrl+Z to suspend the process.
The reason for this is that the empty except: catches
everything, including the KeyboardInterrupt
that is raised when you press Ctrl+C. Instead, what you'll most
likely want is:
try:
...
except Exception:
...
This catches the exceptions you're normally interested in but leaves others
like KeyboardInterrupt or SystemExit unharmed.
No more except: for me!
fman is a file manager with a Python API. If you liked this post, you should check it out!