Explaining the Difference between Exiting Functions with exit() and raise in Python

I’m writing a function deleting all JSON schemas on a server and I want an explicit confirmation that the user knows what he’s doing. I want to confirm his intentions. I’m wondering if using exit with a message/error code is a proper way (raise is better? ) + how to test this flow + how to differentiate between 2 exit statements at hand (exit() VS sys.exit())

Pavol Kutaj
2 min readJun 30, 2023

Exiting a Python Function with exit VS raise <error>

  • I am using sys.exit() which has a similar functionality to exit()
def confirm(intention: str) -> None:
if intention != "yes I am serious":
sys.exit("Confirmation failed. Exiting..."
  • exit() or sys.exit() raise SystemExit exception.
  • However, using raise to raise a proper exception instead of calling exit() would enable handling errors in a specific way, e.g.
def confirm(intention: str) -> None:
if intention != "yes I am serious":
raise ValueError("Confirmation failed")
  • Elsewhere in the code, you may be catching the exception to allow handling it in a way that makes sense for the program (save a file before exiting, logging, etc..) and re-raising it to finally exit

On exit() VS sys.exit(): one for REPL another for programs

  • Both raise the SystemExit exception.
  • exit() is intended for use in the interactive shell.
  • sys.exit() is intended for use in programs.
  • sys.exit() is recommended for use in production code.

In pytest unit testing of sys.exit(), use pytest.raises() context manager with SystemExit exception type

import pytest
def test_confirm():
intention = "no"
with pytest.raises(SystemExit):
confirm(intention)

intention = ""
with pytest.raises(SystemExit):
confirm(intention)

intention = "yes I am serious"
confirm(intention)

--

--

No responses yet