As JBernardo pointed out, sys.exit()
raises an exception. This exception is SystemExit. When it is not handled by the user code, the interpreter exits cleanly (a debugger debugging the program can catch it and keep control of the program, thanks to this mechanism, for instance)—as opposed to os._exit()
, which is an unconditional abortion of the program.
This exception is not caught by except Exception:
, because SystemExit
does not inherit from Exception
. However, it is caught by a naked except:
clause.
So, if your program sees an exception, you may want to catch fewer exceptions by using except Exception:
instead of except:
. That said, catching all exceptions is discouraged, because this might hide real problems, so avoid it if you can, by making the except
clause (if any) more specific.
My understanding of why this SystemExit
exception mechanism is useful is that the user code goes through any finally
clause after a sys.exit()
found in an except
clause: files can be closed cleanly, etc.; then the interpreter catches any SystemExit
that was not caught by the user and exits for good (a debugger would instead catch it so as to keep the interpreter running and obtain information about the program that exited).