gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 10:27:24 27 4
gpt4 key购买 nike

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

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com