如何处理异常?

时间:2011-09-23 12:25:30

标签: c++ exception exception-handling

#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:

我知道通过从析构函数中抛出异常我违反了基本的c ++法则但我仍然想知道他们是否可以处理异常。

4 个答案:

答案 0 :(得分:4)

您的析构函数在try - catch块之外运行 - t的范围是main函数。但是从析构函数中提出异常是 Bad IdeaTM

答案 1 :(得分:3)

必须在try块中创建测试对象:

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

和完整版:

 #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;
    }
}

答案 2 :(得分:3)

你的尝试块中没有任何内容。试试这个:

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

此外,通常在析构函数中抛出异常是一个坏主意(与大多数规则一样,也有例外)。

答案 3 :(得分:1)

为什么不在try块中显式调用析构函数?