Explaining ‘exit(1)’ in Python
The aim of this page📝 is to explain the following encounter in code
env = os.environ["ENV"]
tag["env"] = env
except KeyError as e:
logger.error("Required ENV not found")
exit(<code>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
- bash does not support exceptions (PowerShell does) therefore the use of
exit(0/1)in Python is idiomatic in the context of infrastructure as code and a combination of Python/Bash scripts
0is a success,
1-255are errors and it is essential to follow conventions here
exit(0)means a clean exit without any errors / problems -> A zero error code means a successful exit.
exit(1)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
1to mean no-match-found and
2to report other errors.
- 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.