A bare except looks like a safe way to keep a loop going when one job fails. It also catches things that aren’t errors at all.
In this script eight jobs run one after another, each wrapped in a try block with a bare except and pass. Pressing Control C partway through doesn’t stop it. Python raises KeyboardInterrupt inside the running job, the bare except catches it like any other failure, and the loop moves on. All eight jobs finish and the script exits with code zero, as if nothing happened.
The reason is the exception family tree. Exception is only one branch under BaseException. KeyboardInterrupt and SystemExit sit beside it, on purpose, so that ordinary error handling doesn’t trap them. A bare except catches everything under BaseException, and that includes both. Calling sys.exit inside that try gets swallowed the same way.
Writing except Exception instead keeps the same behaviour for real errors, but lets Control C and sys.exit pass straight through, and the script stops the moment you ask it to. If you really need to catch everything, for example to log and clean up, catch BaseException explicitly and raise it again.
#python #exceptions #coding
source
