divide by zero exception

Hi everyone,I tried to catch an exception which works for about 2 seconds but then the program still for some reason crashes on me I will get the output 2maybe you tried to devide by zero" but straight after the program still crashes,does anyone know how I can fix this and also why it still crashes
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


int main()
{
    int a,b,c;
    cout << "enter first number" << endl;
    cin >> a;

    cout << "enter second number" << endl;
    cin >> b;

    try{


     if(b == 0){

        throw "error";
        c = a/b;
     }
    }catch(...){

         cout << "maybe you tried to deveive by zero";
    }
     c = a/b;
     cout << c;
}
Last edited on
Everything after the try catch block will always run, no matter if an exception was thrown earlier or not, so if b is zero you'll be dividing by zero on line 24.
that makes sense thanks =)

is there anyway I could ask he user then to re-enter the number if the input is zero and then calculate it if the b variable is not 0?

I'm guessing some sort of loop but I'm not sure how I could implement it with the try-catch block there
A simple do/while loop around the try catch block is what you need:
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
#include <iostream>
using namespace std;

int main()
{   int a,b,c;
    bool done = false;
    
    do
    {   cout << "enter first number" << endl;
        cin >> a;

        cout << "enter second number" << endl;
        cin >> b;
        
        try 
        {   if (b == 0)
                throw "error";
            c = a/b;
            cout << c << endl;
            done = true;
        }
        catch(...)
        {   cout << "maybe you tried to divide by zero";
        }
    }
    while (! done); 
    return 0;
}
Last edited on
thanks AA =)
Topic archived. No new replies allowed.