exception specification of overriding function is more lax than base version

  • A+
Category:Languages

I want to custom an Exception class, here's the code:

class TestException : std::exception{   public:   const char *what() const override {     return "TestException";   } }; 

I used Clion and the IDE give me a warning on the function what():exception specification of overriding function is more lax than base version

But if I build the code with gcc, there's no warning came out. I used c++ 14, gcc 6.5.0

Can anybody help to explain what does the warning mean and can I just ignore it?

 


what from std::exception is a virtual function and a virtual function in a derived class cannot have a laxer exception specification than the function it overrides in the base class.

This is mentioned in the section on "Exception specifications" in the standard.

18.4 Exception specifications [except.spec]
...
4. If a virtual function has a non-throwing exception specification, all declarations, including the definition, of any function that overrides that virtual function in any derived class shall have a non-throwing exception specification, unless the overriding function is defined as deleted.

And the example given (which is somewhat similar to the code in the question) illustrates this as well.

struct B  {    virtual void f() noexcept;    virtual void g();    virtual void h() noexcept = delete;  }; struct D: B  {    void f(); // ill-formed    void g() noexcept; // OK    void h() = delete; // OK  };  

The declaration of D::f is ill-formed because it has a potentially-throwing exception specification, whereas B::f has a non-throwing exception specification.

The solution is to change your code like:

class TestException : std::exception{   public:   const char *what() const noexcept override {     return "TestException";   } }; 

See compilation here.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: