#include<iostream>
using namespace std;
class test
{
public:
test()
{
cout<<"hello";}
~test()
开发者_如何学Python {
cout<<"hi";
throw "const";
}
void display()
{
cout<<"faq";
}
};
int main()
{
test t;
try{
}
catch(char const *e)
{
cout<<e;
}
t.display();
}
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.
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.
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).
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;
}
}
Why not just call the destructor function explicitly in try block?
精彩评论