C++ catch block is not catching exception

  c++, exception, try-catch

The following code is still crashing instead of having try-catch block. I use the g++ compiler on Window 10.

#include <iostream>
using namespace std;


int main() {
    int top = 90;
    int bottom = 0;

    try
    {
        cout << "top / 2 = " << (top / 2) << endl;

        cout << "top divided by bottom = ";
        cout << (top / bottom) << endl;

        cout << "top / 3 = " << (top / 3) << endl;
    }
    catch(...)
    {
        cout << "something has gone wrong!" << endl;
    }
    cout << "Done." << endl;
    return 0;
}

Then I tried the following:

#include <iostream>

int main() {
    try {
        throw 0;
    }
    catch(...) {
        std::cout << "Exception occured"! << endl;
    }
    return 0;
}

This one works fine. I mean the catch block here catches the thrown exception.

Source: Windows Questions C++

LEAVE A COMMENT