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. Here is an example code snippet:
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 assert
statement to check the input arguments before the operation, which is more efficient and will raise AssertionError
if the condition is not met
def divide(a, b):
assert b != 0, "Cannot divide by zero."
return a / b
try:
divide(10, 0)
except Exception as e:
print(e)
It will raise AssertionError
with the message "Cannot divide by zero."