Search code examples
pythonexceptionerror-handlingconditional-statements

Throw exceptions in logically impossible situations?


I wonder if it is a good practice or a waste of code to throw an exception in logically impossible condition.

Example:

def __init__(self, type, list_of_variables):
        if type == "var":
            rand_index_var = random.randint(0,len(list_of_variables)) # Since this rand is created from 'list_of_variables'
            if len(list_of_variables) >= rand_index_var: # It is impossible that this condition will fail, at least that a non human error would raise it
                self.symbol = list_of_variables[rand_index_var]
            else:
                raise Exception(f"list index out of range {rand_index_var}")

I would probably maintaing the current version, as there might be an exceptionally rare scenario caused by an OS malfunction, hardware issues, or other factors.


Solution

  • If something is literally impossible, it is a waste of everyone's time to even test for it. There is no point writing code that can never be executed. Indeed, it makes more work for other people; e.g. someone reading the test coverage report, someone in the future trying to understand the code.

    If the something should not happen (but might), then it is a "toss up" whether or not to test for it:

    • If the something is likely to cause significant damage if it is occurs, then an explicit test is warranted.

    • If it is objectively harmless, or if it would trigger an exception anyway, then an explicit test is redundant.

    In your example, if rand_index_var was ever out of range, then

        list_of_variables[rand_index_var]
    

    would raise an exception. So this falls into the "don't test for it" bucket ... whether or not it is literally impossible.

    If you really want to, you could add a comment. I wouldn't bother since it should be obvious to a reader of the code that the scenario is impossible.