How to terminate a program using throw in C++

1 Answer

0 votes
#include <iostream>

class Example
{
private:
    int X;
    const int MIN = 5;
public:
    Example(int _x) : X(_x) {}

    bool getX() const {
        try
        {
            if (X < MIN) {
                throw; // Program terminated here
            }
        }
        catch (bool b) {
            std::cout << "catch (bool b) exception getX()\n";

        }
        catch(...) {
            std::cout << "catch(...) exception getX()\n";
        }
        
        return X;
    }
};

int main()
{
    Example *p = NULL;
    try
    {
        p = new Example(2);
        int val = p->getX();
        delete p;
    }
    catch(...) {
        std::cout << "catch(...) exception main()\n";
    }

    std::cout << "end main()";
}


/*
run:

terminate called without an active exception
Aborted

*/

 



answered Jan 30, 2025 by avibootz

Related questions

1 answer 158 views
1 answer 168 views
1 answer 251 views
1 answer 139 views
...