Which exception should be raised when a required environment variable is missing?

Well most built in concrete exception classes are for specific use cases, and this one does not really fit in any but RuntimeError. But I would advise you to use a custom Exception subclass.


By default KeyError is already raised when an environment variable doesn't exist. os.environ["THISENVDOESNTEXIST"]

Furthermore you can supply a default variable if the env variable doesn't exist. Doing this won't raise the error. os.environ.get("THISENVDOESNTEXIST", "defaultvalue")

Code executed:

Python 3.7.4 (tags/v3.7.4:e09359112e, Jul  8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.environ["THISENVDOESNTEXIST"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Tin\AppData\Local\Programs\Python\Python37\lib\os.py", line 678, in __getitem__
    raise KeyError(key) from None
KeyError: 'THISENVDOESNTEXIST'
>>> os.environ.get("THISENVDOESNTEXIST", "defaultvalue")
'defaultvalue'

If you want to raise your own custom error you can do this:

class MyException(Exception):
  pass

try:
  os.environ["THISENVDOESNTEXIST"]
except KeyError as e:
  raise MyException("Tried accessing an environment variable that does not exist")

You could always create a custom exception

https://www.programiz.com/python-programming/user-defined-exception https://docs.python.org/3/tutorial/errors.html

Ive used this guide before:

Something simple like

class UnconfiguredEnvironment(Exception):
    """base class for new exception"""
    pass

if not os.environ.get("URL",None):
    raise UnconfiguredEnvironment

Use the guides to extend as you see fit.