shubhendu mahajan
shubhendu mahajan

Reputation: 816

How to handle the exception?

#include<iostream>
using namespace std;
class test
{
    public:
        test()
        {
            cout<<"hello";}
            ~test()
            {
                cout<<"hi";
                throw "const";
            }
            void display()
            {
                cout<<"faq";
            }
};
int main()
{
    test t;
    try{
    }
    catch(char const *e)
    {
        cout<<e;
    }
 t.display();
}

output:output:

i know by throwing exception from destructor i'm violating basic c++ laws but still i want to know is their any way the exception can be handled.

Upvotes: 3

Views: 184

Answers (4)

chen
chen

Reputation: 11

Why not just call the destructor function explicitly in try block?

Upvotes: 1

Jem
Jem

Reputation: 2275

The creation of your test object must be done inside the try block:

try
{
 test t;
 t.Display();
}

and a full version:

 #include<iostream>
using namespace std;

class test
{
    public:
        test()
        {
            cout << "hello" << endl;
        }

        ~test()
        {
            cout << "hi" << endl;
            throw "const";
        }
        void display()
        {
            cout << "faq" << endl;
        }
};

int main()
{
    try
    {
        test t;
        t.display();
    }
    catch(char const *e)
    {
        cout << e << endl;
    }
}

Upvotes: 3

Steve
Steve

Reputation: 1810

There's nothing in your try block. Try this:

try
{
    test t;
}
catch(char const *e)
{
    cout << e;
}

Also, in general throwing an exception in a destructor is a bad idea (as with most rules, there are exceptions).

Upvotes: 3

Nikolai Fetissov
Nikolai Fetissov

Reputation: 84239

Your destructor runs outside the try-catch block - t's scope is the main function. but then raising exceptions from a destructor is a Bad IdeaTM.

Upvotes: 4

Related Questions