1

This question is not about how to use sys.exit (or raising SystemExit directly), but rather about why you would want to use it.

  1. If a program terminates successfully, I see no point in explicitly exiting at the end.
  2. If a program terminates with an error, just raise that error. Why would you need to explicitly exit the program or why would you need an exit code?
Alex
  • 3,316
  • 4
  • 26
  • 52
  • 1
    A program can e. g. be part of a larger batch/shell script which should react differently if an error occurs. The script shouldn't need to parse the output of the Python program to check for errors if an exit code is much easier to handle. – Michael Butscher Mar 02 '20 at 12:39
  • Are you asking what exit codes are good for…? https://stackoverflow.com/questions/393845/what-is-a-good-linux-exit-error-code-strategy – deceze Mar 02 '20 at 12:47
  • *"I see no point in explicitly exiting at the end."* You are assuming that `sys.exit` can only be called at the end of the program. That's not true! – kaya3 Mar 02 '20 at 12:50
  • For other programmers who want to import your code, they can also react to the termination of your control flow by catching the `SystemExit` or `BaseException`. – Mia Mar 02 '20 at 12:53

1 Answers1

3

Letting the program exit with an Exception is not user friendly. More exactly, it is perfectly fine when the user is a Python programmer, but if you provide a program to end users, they will expect nice error messages instead of a Python stacktrace which they will not understand.

In addition, if you use a GUI application (through tkinter or pyQt for example), the backtrace is likely to be lost, specially on Windows system. In that case, you will setup error processing which will provide the user with the relevant information and then terminate the application from inside the error processing routine. sys.exit is appropriate in that use case.

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252