从构造函数中捕获异常意味着以后我的实例超出范围 [英] Catching exceptions from a constructor means that my instance is out of scope afterward
问题描述
我有一个其构造函数可能会引发异常的类。以下是一些捕获异常的代码:
I have a class whose constructor may throw an exception. Here’s some code that will catch the exception:
try {
MyClass instance(3, 4, 5);
}
catch (MyClassException& ex) {
cerr << "There was an error creating the MyClass." << endl;
return 1;
}
当然,在try / catch之后没有代码可以看到实例
,因为它现在不在范围内。解决此问题的一种方法是分别声明并定义 instance
:
But of course no code after the try/catch can see instance
because it’s now out of scope. One way to resolve this would be to declare and define instance
separately:
MyClass instance;
try {
MyClass instance(3, 4, 5);
}
...
除了我的班级没有适当的零参数构造函数。实际上,在这种情况下,只有这样一个构造函数才有意义: MyClass
对象是不可变的,因为它没有一个数据成员在构造后会更改。如果要添加零参数构造函数,则需要引入一些实例变量,例如 is_initialized _
,然后进行所有方法检查以确保该变量为 true
,然后继续。对于这种简单的模式,这似乎太冗长了。
except that my class doesn’t have the appropriate zero-argument constructor. In fact, this case right here is the only one in which such a constructor would even make sense: the MyClass
object is intended to be immutable, in the sense that none of its data members change after construction. If I were to add a zero-argument constructor I’d need to introduce some instance variable like is_initialized_
and then have every method check to make sure that that variable is true
before proceeding. That seems like far too much verbosity for such a simple pattern.
处理这种事情的惯用方式是什么?我需要吸收它并允许在初始化类的实例之前对其进行声明吗?
What is the idiomatic way to deal with this kind of thing? Do I need to suck it up and allow instances of my class to be declared before they’re initialized?
推荐答案
做内部 尝试
块所需的一切:
try {
MyClass instance(3, 4, 5);
// Use instance here
}
catch (MyClassException& ex) {
cerr << "There was an error creating the MyClass." << endl;
return 1;
}
毕竟,它只在 try
块,表明已成功创建实例
,因此可以使用。
After all, it is only within the try
block that instance
has been successfully created and so can be used.
我确实想知道您的 catch
块是否真的在处理异常。如果您无能为力,请把它传播出去。
I do wonder whether your catch
block is really handling the exception. If you can't do anything to resolve the situation, you should be letting it propagate.
这篇关于从构造函数中捕获异常意味着以后我的实例超出范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!