in C Plus Plus by
How to write a function that uses a return statement to handle error cases?

1 Answer

0 votes
by

Yes, a function can use a return statement to handle error cases. This is often done in programming languages that support exceptions and error handling mechanisms. Here’s an example in Python:

def divide_numbers(num1, num2):
if num2 == 0:
return "Error: Division by zero"
else:
return num1 / num2

In this function, the return statement is used to handle the error case of division by zero. If the second argument is zero, the function returns an error message instead of performing the division. Otherwise, it performs the division and returns the result.

...