try catch exception
Mar 1, 2021 at 10:27am UTC
Lads, I am trying to do HW in a specific way using the exception library.
task: Considering that var. A, B, C will randomly receive values from 0-10, I have to display the value nr. and variable,
if:
A=1,3,5;
B=2,7;
C=rand()%7-4;
The problem with my code is that when variable C receives values which are included in the range of variable A (3,4,5) it reads variable A as an error as well with same value as C, though A received different values than C. ( and the situation is vice-versa).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
class ERR
{
int value;
public :
ERR(int value=NULL){ this ->value = value; }
void what()
{
switch (this ->value)
{
case 1: cout<<"Code error A [" <<this ->value<<"]" <<endl; break ;
case 3: cout<<"Code error A [" <<this ->value<<"]" <<endl; break ;
case 5: cout<<"Code error A [" <<this ->value<<"]" <<endl; break ;
case 2: cout<<"Code error B [" <<this ->value<<"]" <<endl; break ;
case 7: cout<<"Code error B [" <<this ->value<<"]" <<endl; break ;
}
}
void what1()
{
switch (this ->value)
{
case 3: cout<<"Code error C [" <<this ->value<<"]" <<endl; break ;
case 4: cout<<"Code error C [" <<this ->value<<"]" <<endl; break ;
case 5: cout<<"Code error C [" <<this ->value<<"]" <<endl; break ;
case 6: cout<<"Code error C [" <<this ->value<<"]" <<endl; break ;
case 7: cout<<"Code error C [" <<this ->value<<"]" <<endl; break ;
}
}
};
int main()
{
srand(time(0));
int A,B,C,R;
try
{
A=rand()%11;
B=rand()%11;
C=rand()%11;
R=A+B-C;
cout<<"A=" <<A << " B=" <<B << " C=" <<C << " R= " <<R<<endl;
if (A==1) throw ERR(1);
if (A==3) throw ERR(3);
if (A==5) throw ERR(5);
if (B==2) throw ERR(2);
if (B==7) throw ERR(7);
if (C==3) throw ERR(3);
if (C==4) throw ERR(4);
if (C==5) throw ERR(5);
if (C==6) throw ERR(6);
if (C==7) throw ERR(7);
}
catch (ERR&e)
{
e.what();
e.what1();
}
return 0;
}
Mar 1, 2021 at 12:47pm UTC
The class ERR does not make any differences when it comes to the value, where 3 and 5 do overlapp.
What you can do to make the difference between A and C is e.g. multiply the value of A with 100. Then the switch would look like:
1 2 3 4 5 6 7
void what()
{
switch (this ->value)
{
case 100: cout<<"Code error A [1]" <<endl; break ;
...
Mar 1, 2021 at 4:50pm UTC
@coder777, thanks so much, I could identify the problem however couldn't think out a simple solution to it!
Topic archived. No new replies allowed.