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!
Raised when an error does not fall under any other category. Raised by next() function to indicate that there is no further item to be returned by iterator. Raised by parser when syntax error is encountered.
Raising an exception is a technique for interrupting the normal flow of execution in a program, signaling that some exceptional circumstance has arisen, and returning directly to an enclosing part of the program that was designated to react to that circumstance.
As a Python developer you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword.
Environment variables are implemented through the os package, specifically os. environ.
If the error message states that the environment variable is not set, IT MEANS PRECISELY THAT ! The most likely reason is that your spelling of the variable name is WRONG.
It's your application- as long as you document it and clearly indicate the exception that will be thrown in the specific case of a missing configuration value, you can use any exception you like. If you do want a very specific indication of a missing value, you might consider writing your own ConfigurationSettingMissing exception:
Clarification: The exceptions are produced when anything unexpected happened. The program might not be able to find a file in the target location and hence program produces an exceptions. The exception produced, then terminates the program. 5. Which is the universal exception handler class?
The exceptions should always be given in proper sequence to ensure that no code remains unreachable. If not done properly the code might never be used in a program. 14. Which class is used to handle the input and output exceptions? Clarification: There is a specific class to handle each type of exceptions that might be produced in a program.
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.
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 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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With