+ 1
Why is throwing necessary
Hey guys. In case of the example where the users input is to be divided we check the second input not to be zero. In case it is zero an exception is thrown and handled in the catch block. So far so good, I get that. But instead of throwing the exception I could also print the "cout" right away. Is the concept used not to have a possibility huge amount of nested "if then else" or "switch" cases? Cheers.
2 Answers
+ 3
I assume that by printing the cout you mean printing the error message you would print while handling the exception (in the catch block), directly in the if block.
In general, the code where you throw your exception won't be in the same function as the code where you handle it.
Instead of testing if the second input is equal to 0 and throw the exception, try doing the division by 0. In this case, it's the division function that will throw the exception, and you will still be able to handle it in your function.
0
Right.
So if it wasn't a divide by zero exception that is handled by the division operator itself, I could separate my functional code from the code handling the exception.
Good point! Thanks