Exception Handling

Good day everyone,
Please i need your help with my my code which does not recognize the exceptional handling code.
Here is my code but it always skips and says "Go and buy some milk."#include <iostream>

using namespace std;

int main()
{
int donuts, milk;
double dpg;

try
{
cout << " Enter the number of donuts: ";
cin >> donuts;
cout << " enter the number of galsses of milk: ";
cin >> milk;
if(milk <= 0);
{
throw donuts;
}

dpg = donuts/static_cast<double>(milk);
cout << donuts << " donuts.\n"
<< milk << " glasses of milk.\n"
<< " You have " << dpg
<< " donuts for each glass of milk.\n";

}

catch(int e)
{
cout << e << " donuts and No milk \n";
cout << " Go and buy some milk\n";
}

cout << " End of program.\n";

return 0;
}

Thank you for your help!!!

Line 16: there's an ";" after if, so it will always throw.
Instead of
1
2
3
4
if(milk <= 0);
{
throw donuts;
}


You must write
1
2
3
4
if(milk <= 0)
{
throw donuts;
}
1
2
3
4
5
// if( milk <= 0 ); // *** get rid of this semicolon
if( milk <= 0 )
{
    throw donuts;
}


As a general principle, avoid using exceptions for implementing control-flow.
Agreed. You're effectively using an exception as an "else" block, which is terrible.

This:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
try
{
    cout << " Enter the number of donuts: ";
    cin >> donuts;
    cout << " enter the number of galsses of milk: ";
    cin >> milk;
    if(milk <= 0)
    {
        throw donuts;
    }

    dpg = donuts/static_cast<double>(milk);
    cout << donuts << " donuts.\n"
        << milk << " glasses of milk.\n"
        << " You have " << dpg
        << " donuts for each glass of milk.\n";
}
catch(int e)
{
    cout << e << " donuts and No milk \n";
    cout << " Go and buy some milk\n";
}


Is just as easily (or even more easily written) as this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
cout << " Enter the number of donuts: ";
cin >> donuts;
cout << " enter the number of galsses of milk: ";
cin >> milk;
if(milk > 0)
{
    dpg = donuts/static_cast<double>(milk);
    cout << donuts << " donuts.\n"
        << milk << " glasses of milk.\n"
        << " You have " << dpg
        << " donuts for each glass of milk.\n";
}
else
{
    cout << e << " donuts and No milk \n";
    cout << " Go and buy some milk\n";
}
Topic archived. No new replies allowed.