Exception Handling

Why is exception handling needed? For example, if my function divides two numbers and returns quotient, I can check for value of b before I divide to ensure it's not 0. For example,
double divide (int a, int b)
{
if (b == 0)
cout << "Can't divide by 0 \n";
else return a/b;
}
Wouldn't above code do same thing that Exception handling will do with so much code?
What am I missing?
Well if you pass 0 to the b parameter the function will execute undefined behavior. (Probably crash).

And no. Exceptions break out of the functions and pass a special value to a catch statement, and you can handle it there.
Last edited on
Your function is returning a value of type double to the caller. What does it equal when you decide you can' t perform the division? How does the calling code know that the double it got from calling your function is not the true result of division? The function that called your function cannot see what it printed to cout.

Granted, doubles have special values (infinities and not-a-numbers) that you could return to let the caller know, but another type may not have that luxury: this would be the case where a function cannot satisfy postconditions, which is one of the situations where exceptions are expected (others are failures to establish invariants and, for wide-contract functions, invalid preconditions)
Topic archived. No new replies allowed.