W3docs

Which exception should I raise on bad/illegal argument combinations in Python?

You can raise the ValueError exception when you encounter bad or illegal argument combinations in Python.

You can raise the ValueError exception when you encounter bad or illegal argument combinations in Python. Note that TypeError is typically preferred when arguments have the wrong data type, while ValueError is used for correct types but invalid values. Here is an example code snippet:

Raise a ValueError manually in Python

def divide(a, b):
    if b == 0:
        raise ValueError("Cannot divide by zero.")
    return a / b

try:
    result = divide(10, 0)
except ValueError as e:
    print(e)

In this example, if the value of b passed to the divide function is 0, the ValueError exception is raised with the message "Cannot divide by zero." The try block surrounding the call to divide is used to catch and handle the exception, in this case printing the error message.

Alternatively, you can use an assert statement to check input arguments before the operation, which is more efficient and will raise AssertionError if the condition is not met. Warning: assert statements are stripped when Python runs with the -O (optimize) flag, making them unsafe for production input validation.

AssertionError example in Python

def divide(a, b):
    assert b != 0, "Cannot divide by zero."
    return a / b

try:
    divide(10, 0)
except AssertionError as e:
    print(e)

It will raise AssertionError with the message "Cannot divide by zero."