How are exceptions better than if-statements? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How are exceptions better than if-statements?

If I modify the example code as: #include <iostream> using namespace std; int main() { int num1; cout <<"\nEnter the first number:"; cin >> num1; int num2; cout <<"\nEnter the second number:"; cin >> num2; cout << "\n= " << num1 << " / " << num2 << endl; if (num2 > 0) cout <<"\nResult:"<<num1 / num2; else cout << "\nResult: cannot divide by zero (0)" << endl; } How are exceptions better than this if statement? Aside from OS signals, I'm not sure that trying and catching an exception is the better way to go.

2nd Apr 2017, 9:42 PM
Mike L.
Mike L. - avatar
4 Answers
+ 5
in your case you are handling only positive values of num2. You'llget "Result: cannot divide by zero" even if you divide by a negative number. Of course you can get around the problem using another condition [if (num2>0 || num2<0)]. Using exception handling would simplify things in your case and specially in more complicate scenarios.
2nd Apr 2017, 11:15 PM
seamiki
seamiki - avatar
+ 2
@Mile L. tell me where I was wrong? I suggested you the two conditions for the if statement to avoid using exceptions. using exceptions you would only evaluate one condition (num2 == 0). Again it would male life easier specially in more complicate scenarios.
3rd Apr 2017, 9:59 AM
seamiki
seamiki - avatar
0
seamiki , Your right, and wrong at the same time. I should have checked for the error condition, and left the "else" to handle all other cases. Similar to the example where they only throw the exception if num2 equals​ zero.
4th Apr 2017, 3:33 AM
Mike L.
Mike L. - avatar
0
JPM7, Thanks for the evidence of my suspicions. While I agree with your post, and the other references, I can also see where using try-catch blocks can be a more elegant way to control flow within the program ... albeit a violation of the intent of the construct.
4th Apr 2017, 3:39 AM
Mike L.
Mike L. - avatar