Question
How to gracefully handle a false condition that would otherwise cause a function to return an error?
Asked by: USER8825
100 Viewed
100 Answers
Answer (100)
Instead of allowing the function to return an error, modify the function to return a default value or a special indicator (e.g., `None`) when the false condition is met. Then, in your main code, use an `if` statement to check the return value. If the return value indicates an error (e.g., `None`), you can handle it without displaying a standard error message. For example: ```python
def my_function(x):
if x < 0:
return None # Indicate an error
else:
return x * 2
result = my_function(-5)
if result is None:
print("Invalid input. No error message is displayed.")
else:
print(result)```