Explaining ‘exit(1)’ in Python

The aim of this page📝 is to explain the following encounter in code

    try:
env = os.environ["ENV"]
tag["env"] = env
except KeyError as e:
logger.error("Required ENV not found")
exit(1)
  • is sending an error code — usually to a bash script that called the python one
  • when a UNIX/bash program ends, it returns an 8-bit code and
  • bash does not support exceptions (PowerShell does) therefore the use of in Python is idiomatic in the context of infrastructure as code and a combination of Python/Bash scripts
  • conventionally, is a success, are errors and it is essential to follow conventions here
  • means a clean exit without any errors / problems -> A zero error code means a successful exit.
  • means there was some issue/error / problem and that is why the program is exiting; any non-zero exit code is treated as an abnormal exit
  • in addition, this is not Python-specific and is conventional
  • in UNIX/Linux utilities the error code indicates what the problem was.

Many programs document specific exit codes to report certain failure modes, for instance uses to mean no-match-found and to report other errors.

https://stackoverflow.com/a/40858196/11082684

  • the disadvantage of not having exceptions and using return codes is that

that they clutter the caller. The caller must check for errors immediately after that call. Unfortunately, it’s easy to forget. For this reason, it is better to throw an exception when you encounter an error.

https://medium.com/@ansujain/clean-code-error-handling-db0062044cb5

LINKS

--

--

Infrastructure Support Engineer/Technical Writer (snowplow.io) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Pavol Kutaj

Infrastructure Support Engineer/Technical Writer (snowplow.io) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com