try catch unexpected result?

May 22, 2016 at 7:56pm
hi guys so when I enter a valid number that is not 0 the try and catch block still gets called and it prints cannot divide by zero even when x and y are not equal to zero,what is happening? and how do i fix it

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
 #include <iostream>

using namespace std;


int main()
{
   try{
   int x;
   int y;
   int result;

   cin >> x;
   cin >> y;

    result = x / y;
   if(x || y == 0){

    throw 99;

   }
   }catch(int x){

       cout << "cannot divide by 0 :" << x;

}

}
May 22, 2016 at 8:02pm
1
2
3
4
if(x || y == 0)
{
    throw 99;
}
This is true if x != 0. In C++ false == 0 , != 0 means true.
May 22, 2016 at 8:07pm
not too sure what you mean Tom,But I thought x !=0 and y !=0 therefore the catch block should not be called :s
Last edited on May 22, 2016 at 8:07pm
May 22, 2016 at 8:17pm
if(x || y == 0)
Perhaps you meant
if (x ==0 || y == 0)

Shouldn't you be checking for divide-by-zero before you try to actually do the division? Not much point checking afterwards.
Last edited on May 22, 2016 at 8:21pm
May 22, 2016 at 8:24pm
closed account (E0p9LyTq)
All you need to check for is the divisor is not zero. Zero divided by any non-zero number is zero.

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
#include <iostream>

int main()
{
   int x;
   int y;

   std::cout << "x: ";
   std::cin >> x;
   std::cout << "y: ";
   std::cin >> y;

   try
   {
      if (y == 0)
      {
         throw "error";
      }
      int result = x / y;
      std::cout << "result: " << result << "\n";
   }

   catch(...)
   {
      std::cout << "\ncannot divide by 0:\n";
   }
}
May 22, 2016 at 8:52pm
thanks guys just a quick question on the same note how come I cannot put result = x/y; after the try catch block? it tells me that it's not declared in this scope

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


#include <iostream>

using namespace std;


int main()
{
   try{
   int x;
   int y;
   int result;

   cin >> x;
   cin >> y;

   if(x == 0 || y == 0){

    throw 99;

   }

   
   }catch(int x){

       cout << "cannot divide by 0 :" << x;

}

result = x /y; // error
}

May 22, 2016 at 8:56pm
closed account (E0p9LyTq)
result is being declared inside your try block, you are accessing it outside the try block.
May 22, 2016 at 8:58pm
I see that in this code, even if you detect that y is zero and that you are thus going to try to divide by zero, you still actually try to do a divide by zero.

If you detect that there is going to be a divide-by-zero, you should then not do the divide-by-zero.
May 22, 2016 at 9:03pm
Thanks guys that makes sense much appreciated
Topic archived. No new replies allowed.