+ 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.

24th Jan 2019, 4:16 PM
ChrA
ChrA - avatar
2 Respostas
+ 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.
24th Jan 2019, 5:03 PM
Zen
Zen - avatar
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
24th Jan 2019, 5:45 PM
ChrA
ChrA - avatar