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

Viewed 10040

The title pretty much sums it up already.

I have a piece of code that calls os.getenv to get both a URL as well as a token in order to connect to a service. The code lives in a module and will only be imported from there, i.e. it's not a script.

It's not a huge issue at all, since I really only need to crash and display the message saying that there are unset values, but it got me thinking about which of Python's built-in exceptions would be the best fit.

I found the EnvironmentError, but that seems to function as base class from which IOError and other OS related exceptions inherit.

Would it be as simple as a ValueError, as it's really just a value that's missing?

Thanks!

4 Answers

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")

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.

You can make your own exceptions for specific cases by inheriting from Exception

class MissingEnvironmentVariable(Exception):
    pass


def get_my_env_var(var_name):
    try:
        envvar = os.environ[var_name]
    except KeyError:
        raise MissingEnvironmentVariable(f"{var_name} does not exist")
Related