小能豆

Throw exceptions in logically impossible situations?

py

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.


阅读 85

收藏
2023-12-12

共1个答案

小能豆

In general, it’s a good practice to include explicit checks for logically impossible conditions to catch potential bugs early and make the code more robust. However, in your specific example, the condition if len(list_of_variables) >= rand_index_var: seems redundant because rand_index_var is generated using random.randint(0, len(list_of_variables)), and therefore, it should always be less than or equal to len(list_of_variables).

In this case, you can simplify your code by removing the unnecessary check:

def __init__(self, type, list_of_variables):
    if type == "var":
        rand_index_var = random.randint(0, len(list_of_variables))
        self.symbol = list_of_variables[rand_index_var]

If the condition is logically impossible based on the algorithm or the logic you’ve implemented, adding an exception for it might be considered redundant and could be seen as noise in the code. However, in some cases, adding such checks can be helpful for documenting assumptions and preventing unexpected behavior if, for some reason, the assumptions are violated in the future.

In summary, it depends on the specific context and the potential impact of such a condition being violated. If the condition is genuinely impossible due to the logic of your code, removing the check might make the code cleaner. However, if there’s any doubt or the impact of a violation is severe, keeping the check and raising an exception is a safer approach.

2023-12-12