是否可以在 C++ 中提供异常? 虚拟(纯)类成员?
如果是这样怎么办?
我知道如何为成员提供异常规范,例如
class SOMEClass
{
public:
void method(void) throw (SOMEException);
virtual void pure_method(void) = 0;
};
“以便方法”仅抛出“SOMEException”。 如果我想确保SOMEClass
的子类为pure_method
抛出SOMEException
,是否可以添加异常规范? 这种方法是否可行,或者我是否需要更多地了解异常和抽象方法以找出为什么可以(不)可以完成?
If so how?
I know how to provide exception specifications for members such as
class SOMEClass
{
public:
void method(void) throw (SOMEException);
virtual void pure_method(void) = 0;
};
So that the method
throws only SOMEException
. If I want to ensure that sub-classes of SOMEClass
throw SOMEException
for pure_method
, is it possible to add the exception specification?. Is this approach feasible or do I need to understand more on exceptions and abstract methods to find out why it can(not) be done?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,纯虚拟成员可以有异常规范。
我建议您阅读以下内容:http://www.gotw.ca/publications/mill22.htm<不过,在过多涉及异常规范之前。
Yes, a pure virtual member can have an exception specification.
I recommend you to read this: http://www.gotw.ca/publications/mill22.htm before getting too much involved in exception specifications, though.
是的,我很确定在纯虚函数上放置了异常规范,尽管我还没有尝试过。
然而,大多数 C++ 专家都认为,除了 nothrot 规范之外,C++ 异常规范几乎毫无用处,虽然它们是对编译器的提示,但它们的强制执行方式与 Java 等中的方式不同。
除非您将适当的 catch-all 块放入纯虚函数的每个实现中,否则您根本无法保证它只会抛出异常规范中列出的异常。
Yes, I'm pretty sure put an exception specification on a pure virtual function although I haven't tried it.
However, most C++ experts agree that apart from the nothrow specifications, C++ exception specifications are pretty useless and while they are a hint to the compiler, they are not enforced the same way that they are in, for example, Java.
Unless you put the appropriate catch-all block into each and every implementation of your pure virtual function, you simply cannot guarantee that it will only throw the exceptions listed in your exception specification.
有可能的。 但仅对于 throw() 情况才合理。 每次派生类忘记在其“action”方法声明上添加“throw()”规范时,编译器都会向您发出警告。
It is possible. But reasonable only for throw() case. Compiler will warn you every time derived class forgets add "throw()" specification on its "action" method declaration.