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

标签 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)

};

最佳答案

语言本身没有以任何可检测的方式“无效”对象的概念。

如果异常指示无法创建有效对象,则不应在构造函数中处理它;要么重新扔掉它,要么一开始就不要捕获它。然后程序将离开正在创建的对象的范围,并且将不可能错误地访问它。

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

关于C++ 在构造函数中捕获异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26169189/

相关文章:

c++ - 其他线程是否会在合理的时间内看到对 `volatile` 字大小变量的写入?

c# - 在 System::Collections::Generic::List<T> 类型的列表中列出是可能的吗?

c++ - Glvalue 引用一个基类子对象

java - 在 jar 里找不到我的主类

python - 在解析器中报告非 fatal error 的 Pythonic 方式是什么?

android - 在 ffmpeg 中读取 JPEG

java - 为什么抛出异常的方法的调用者在这种情况下不必处理异常?

c++ - 可移动但不可复制的异常

iphone - iPhone/Objective-C的try-catch异常处理实践

.net - 无法创建抽象类?