2 ms·
"Nobody writes code to defend against an exception being raised on literally any line" says the article, but isn't that why we have e.g. Python's context manage
by ptx 11y ago
"Nobody writes code to defend against an exception being raised on literally any line" says the article, but isn't that why we have e.g. Python's context managers and Java's try-with-resources? In Python, KeyboardInterrupt can already be raised anywhere and any object could have any method unexpectedly replaced with one that starts throwing exceptions.
But it's a good point that it creates a greater risk of raising an exception in the cleanup part of the context manager or try/finally, where one might normally try to avoid it by being extra careful:
try:
try:
time.sleep(10) # or some interesting function
except KeyboardInterrupt:
print("Unexpectedly aborted, but that's fine.")
finally:
print("Cleaning up!")
time.sleep(10) # or some important cleanup
except KeyboardInterrupt:
print("Abort was aborted! Now things are all screwed up!")
So one should probably be careful not to press ^C more than once when aborting a Python program, I guess.