C ++在构造函数中捕获异常

时间:2014-10-02 20:33:06

标签: c++ exception exception-handling constructor

如何在使用异常时保护自己不使用未完全创建的对象? 我应该抓住构造函数吗?或者这可能是不好的做法?如果我将捕获构造函数对象将被创建。

#include <stdio.h>

class A
{
public:
    A()
    {
        try {
            throw "Something bad happened...";
        }
        catch(const char* e) {
            printf("Handled exception: %s\n", s);
        }
        // code continues here so our bad/broken object is created then?
    }
    ~A() 
    { 
        printf("A:~A()"); 
    }

    void Method()
    { // do something
    }
};

void main()
{
    A object; // constructor will throw... and catch, code continues after catch so basically we've got 
              // broken object.

    //And the question here: 
    //
    //* is it possible to check if this object exists without catching it from main? 
    // &object still gives me an address of this broken object so it's created but how can I protect myself 
    // from using this broken object without writing try/catch and using error codes?
    object.Method(); // something really bad. (aborting the program)

};

3 个答案:

答案 0 :(得分:9)

语言本身并没有一个对象存在概念的概念&#34;无效&#34;以任何可检测的方式。

如果异常表明无法创建有效对象,则不应在构造函数内处理;要么重新抛出它,要么首先不要抓住它。然后程序将离开正在创建的对象的范围,并且不可能错误地访问它。

如果由于某种原因这不是一个选项,那么您需要以自己的方式将对象标记为&#34;无效&#34 ;;也许在构造函数的末尾设置一个布尔成员变量来表示成功。这是不稳定且容易出错的,所以除非你有充分的理由,否则不要这样做。

答案 1 :(得分:2)

如果在抛出某个异常时对象处于无效状态,那么我会让异常展开调用堆栈,以便可以通知调用者(并因此做出反应)。

但是,如果异常是您可以从中恢复的,则可能值得尝试依赖于您的应用程序。确保你使用类似记录器的东西,甚至只是stderr来表明这种情况正在发生。

答案 2 :(得分:1)

我将建议第一次做一些更像这样的事情:

   try {
        throw "Something bad happened...";
    }
    catch(const std::exception e) {
        cerr << e.what () << endl ; // Better off in the main
        throw ;
    }

这里有两件事:

  1. 除非你的异常处理程序处理异常,否则它应抛出。

  2. 始终使用基于std :: exception的异常类,以便始终可以找出问题所在,如上所示。

相关问题