c++ - 无法捕获 C++ 异常

标签 c++ exception

我想在尝试使用某个类的复制构造函数时捕获异常,这会抛出异常。

#include <iostream>

class dont_copy_me {
public:
    dont_copy_me() {}
    dont_copy_me(const dont_copy_me& rhs) {throw;}
    dont_copy_me(dont_copy_me&& rhs) {throw;}
    ~dont_copy_me() {}
};

int main() {
    try {
        dont_copy_me obj;
        dont_copy_me obj_1(obj);
    } catch(...) {
        std::cout << "exception caught" << std::endl;
    }
    return 0;
}

但我不断得到

terminate called without an active exception
Aborted (core dumped)

怎么了?如何捕获复制构造函数抛出的异常? (因为这就是我所需要的)

最佳答案

实际上抛出这样的异常:

#include <iostream>
#include <stdexcept>

class dont_copy_me {
public:
    dont_copy_me() {}
    dont_copy_me(const dont_copy_me& rhs) {throw std::runtime_error("Fail!");}
    dont_copy_me(dont_copy_me&& rhs) {throw std::runtime_error("Fail!");}
    ~dont_copy_me() {}
};

int main() {
    try {
        dont_copy_me obj;
        dont_copy_me obj_1(obj);
    } catch(...) {
        std::cout << "exception caught" << std::endl;
    }
    return 0;
}

这就是您所需要的。 Here您可以找到标准异常(exception)列表(在“异常(exception)类别”下)。

空的 throw 表达式仅在您已经处理事件异常时才有效:

Rethrows the currently handled exception. Abandons the execution of the current catch block and passes control to the next matching exception handler (but not to another catch clause after the same try block: its compound-statement is considered to have been 'exited'), reusing the existing exception object: no new objects are made. This form is only allowed when an exception is presently being handled (it calls std::terminate if used otherwise). The catch clause associated with a function-try-block must exit via rethrowing if used on a constructor.

来自 here , 强调我的。

关于c++ - 无法捕获 C++ 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28920320/

相关文章:

由 小码哥发布于 2019-03-18 标签:c++openmpshared_ptrdatarace

cpp 文件中的 C++ 值定义和额外限定

Ruby - 救援后如何检查特定异常?

exception - 正确使用错误

java - 如果函数引发异常,如何避免返回值?

c++ - 包装函数只能看到它自己?

c++ - 类内模板化类的 Typedef

c++ - 尝试 Throw Catch C++ 嵌套函数

java - 需要帮助来修复以下代码的 arrayoutofboundary 异常

asp.net - 如何创建详细的错误页面?