dubnde
dubnde

Reputation: 4441

Is it possible to provide exceptions in C++ virtual(pure) class member?

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?

Upvotes: 1

Views: 1941

Answers (3)

Mykola Golubyev
Mykola Golubyev

Reputation: 59834

virtual void action() throw() = 0;

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.

Upvotes: 0

Éric Malenfant
Éric Malenfant

Reputation: 14148

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.

Upvotes: 6

Timo Geusch
Timo Geusch

Reputation: 24351

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.

Upvotes: 0

Related Questions