gpt4 book ai didi

c++ - 如何在抛出异常时阻止构造函数创建对象

转载 作者:可可西里 更新时间:2023-11-01 18:02:18 24 4
gpt4 key购买 nike

当构造函数抛出异常时,如何阻止创建对象?

在下面的示例中,我创建了一个 Month() 类,int month_ 属性的合法值在 1 到 12 的范围内。我实例化了 December,或者 dec ,整数值为 13。应该抛出异常,但对象仍被创建。然后调用析构函数。

如何在抛出异常时中止类实例的创建?

输出

-- Month() constructor called for value: 2
-- Month() constructor called for value: 6
-- Month() constructor called for value: 13
EXCEPTION: Month out of range
2
6
13
-- ~Month() destructor called.
-- ~Month() destructor called.
-- ~Month() destructor called.
Press any key to exit

最小、完整且可验证的示例

#include <iostream>
#include <string>

class Month {

public:
Month(int month) {
std::cout << "-- Month() constructor called for value: " << month << std::endl;
try {
// if ((month < 0) || month > 12) throw 100; Good eye, Nat!
if ((month < 1) || month > 12) throw 100;
} catch(int e) {
if (e == 100) std::cout << "EXCEPTION: Month out of range" << std::endl;
}
month_ = month;
}

~Month() {
std::cout << "-- ~Month() destructor called." << std::endl;
}

int getMonth()const { return month_; }

private:
int month_;
};

int makeMonths() {
Month feb(2), jun(6), dec(13);
std::cout << feb.getMonth() << std::endl;
std::cout << jun.getMonth() << std::endl;
std::cout << dec.getMonth() << std::endl;
return 0;
}

int main() {
makeMonths();
std::cout << "Press any key to exit"; std::cin.get();
return 0;
}

最佳答案

How do I abort creation of a class instance upon a thrown exception?

好吧,你在构造函数中抛出一个异常。但有一个问题:不要捕获它!

如果你捕捉到它,就好像异常从未发生过一样。你捕获了它,所以它不再上升到调用堆栈。所以创建了对象,因为就任何人而言,构造函数都没有抛出异常。

如果从构造函数中删除 catch 子句,您可能会得到如下内容:

-- Month() constructor called for value: 2
-- Month() constructor called for value: 6
-- Month() constructor called for value: 13
terminate called after throwing an instance of 'int'
[1] 28844 abort (core dumped) ./main

在这里,构造函数抛出了一个异常,这次它在构造函数之外的调用堆栈中向上移动,因为没有人在构造函数中捕获它。然后它转到 makeMonths,它也没有被捕获,然后转到 main,它也没有被捕获,因此程序异常终止。

关于c++ - 如何在抛出异常时阻止构造函数创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44853547/

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