问题
The following code is generating the "Looser throw specifier error". Could you please help me to overcome this error?
class base
{
virtual void abc() throw (exp1);
}
void base::abc() throw (exp1)
{
......
}
class sub : public base
{
void abc() throw(exp1, exp2);
}
void sub::abc() throw (exp1, exp2)
{
.....
}
回答1:
The problem comes about because the subclass must be usable wherever the base class can be used, and so must not throw any exception types other than those specified in the base class.
There are three solutions:
- Modify the base class specifier to include every exception type that any subclass might ever need to throw
- Modify every subclass to handle every exception type except those specified in the base class
- Remove the exception specifiers.
I would suggest removing them; they are widely regarded as a bad idea, partly because of issues like this. As Matthieu points out, the Standard Committee agrees, and exception specifiers are due to be deprecated in the next version of the Standard.
回答2:
When you override a virtual method with a throw specifier in a derived class, the method in the derived class cannot throw more exceptions than the method in the superclass. If you were allowed to do this, you could break the contract created by the superclass's public API by overriding methods in a subclass.
In your example, you're saying that base::abc can only throw exp1. However, if you have a pointer of type base which is really pointing to an instance of sub, all of a sudden abc can throw exp2 in addition to exp1.
To fix the problem you need to remove exp2 from the throw specifier in the subclass or add exp2 to the throw specifier of the superclass.
回答3:
Suppose I try
base *b = new sub;
b->abc();
Based on the throw specifier in base::abc, I'd expect that it only throws exp1; but sub::abc says that it might also throw exp2.
If sub::abc can really throw exp2, then add exp2 to the list of what base::abc can throw. If not, then remove it from sub::abc's list.
And better: don't use throw specifiers. For more info, see Can anyone explain C++ exception specifications to me? and http://www.gotw.ca/publications/mill22.htm.
来源:https://stackoverflow.com/questions/5269957/looser-throw-specifier-error-in-c