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

Question:

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!

Asked By: TomMP

||

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:UsersTinAppDataLocalProgramsPythonPython37libos.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")
Answered By: Tin Nguyen

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:
        return os.environ[var_name]
    except KeyError:
        raise MissingEnvironmentVariable(f"{var_name} does not exist")
Answered By: Kathy Rindhoops

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.

Answered By: Serge Ballesta

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.

Answered By: tomgalpin
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.