13

Is it good or bad practice to make pure virtual functions noexcept? I always thought we should not put extra restriction on its implementation classes that their implementation should be no throw since putting this may result in modification in implementation and unnecessary try catch blocks to prevent exception escape. i thought implementation should decide whether function can marked as noexcept not the exception specification should decide implementation?

Can some one please correct me if i am wrong here?

Bharat Ahuja
  • 394
  • 2
  • 15

2 Answers2

8

noexcept isn't about implementations, it's about interface. Is the abstract operation represented by the virtual function one that fundamentally cannot fail? Then make the virtual function noexcept. If the operation could fail theoretically, even if none of the implementations you write can't, don't.

Sebastian Redl
  • 69,373
  • 8
  • 123
  • 157
8

noexcept is part of member function specification, in the same way as its return type, parameter list, and const qualifier. It is there to help users of the function - obviously, at the expense of function's implementers.

If you need to give implementers more flexibility while providing your users with a noexcept function, make a pair of functions - a non-virtual public function with noexcept, and a protected virtual function without noexcept. Make the public noexcept function call virtual implementation, and handle exceptions to hide them from its callers:

class Base {
protected:
    virtual void doSomethingImpl() = 0;
public:
    void doSomething() noexcept {
        try {
            doSomethingImpl();
        } catch(...) {
            // Provide some handling here
        }
    }
};

class Derived : public Base {
    void doSomethingImpl() {
        ... // Implementers have flexibility to throw here
    }
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 1
    I'd say if you need to use this construct, then there is something wrong with your design. To be able to properly handle an implementation's exceptions, the base class would need to know about its derived classes too much. – MicroVirus Apr 15 '16 at 11:16
  • i agree with MicroVirus base class should not assume much about derived classes that why in first place i always hesitate to put noexcept even if operation looks too trivial – Bharat Ahuja Apr 15 '16 at 11:18
  • @MicroVirus Something like this could be useful as defense against implementations that may throw unexpectedly in situations when you have no control of the implementation at all. There is little you can do to handle the exception *and* continue as if nothing has happened, so exception handler there should log and help the rest of the code terminate gracefully. – Sergey Kalinichenko Apr 15 '16 at 11:23