Documentation on exception handling tends to focus on using specific exception types – which is good advice in general.
However there are times I want to run some Python code which under no circumstances throws an exception that isn’t handled and stops the program from running:
For example, a graphical application might run a user-defined script. I don’t know what errors that script could trigger, so it’s not useful to check for specific errors:
try:
run_script_file(filepath)
except:
import traceback
print("Script:", filepath, "failed with error!")
traceback.print_exc()
This works, but code checking tools warn that bare except
should not be used. While I could suppress the warnings in each case, I was considering using except BaseException:
to quiet the warnings.
Is a bare except:
guaranteed to be the equivalent of except BaseException:
or are there subtle differences where a bare except might catch exceptions a BaseException
wouldn’t?
2
From the documentation:
In Python, all exceptions must be instances of a class that derives from BaseException.
Also noted in PEP8 (emphasis mine):
A bare
except
: clause will catch SystemExit and KeyboardInterrupt exceptions, making it harder to interrupt a program with Control-C, and can disguise other problems. If you want to catch all exceptions that signal program errors, useexcept Exception:
(bare except is equivalent toexcept BaseException:
).
So, yes, they’re equivalent.
3