Search code examples
c++oopexceptioninheritancevirtual

c++ objected oriented programming exception failure


So I am creating an exception using inheritence of "exception" library, but I get an error which says looser throw for 'virtual'.

#include <string>
#include <exception>
#include <sstream>

namespace Vehicle_Renting{

using namespace std;

class Auto_Rent_Exception : public std::exception{


protected:
      string error;

   public:
      Auto_Rent_Exception(){
      }
  virtual const string what() = 0;

  virtual Auto_Rent_Exception* clone() = 0;
};

It says : error: looser throw specifier for 'virtual Vehicle_Renting::Auto_Rent_Exception::~Auto_Rent_Exception()' Vehicle_Renting is namespace of my project.


Solution

  • Add the prototype destructor to your derived class from Auto_Rent_Exception.

    virtual ~Auto_Rent_Exception() throw();
    

    On a side note you should be careful about using std::string (or anything that allocates memory dynamically) in an exception class. In case some API function fails (e.g. because there is too little memory left), chances are your std::string constructor will throw std::bad_alloc, hiding the initial exception. Or if you implement an own memory allocator you can possibly create an endless loop of exceptions. It would be better to catch and ignore exceptions from std::string, so that the original exception is propagated (without a description, but still better than nothing/a "wrong" exception).