The following code works just fine:
#include <exception>
using namespace std;
class FileException : public exception { // error occurs here
    int _error;
    // string _error; <-- this would cause the error
public:
    FileException(int error);
    // FileException(string error);
    const char* what() const throw();
};
But as soon as I change the type of _error to string, the following compile error occurs:
Exception specification of overriding function is more lax than base version
The destructor of std::string is not no-throw, which causes the implicit destructor of FileException not no-throw either. But the destructor of std::exception is no-throw, thus there's a compiler error.
You could declare an explicit no-throw destructor:
virtual ~FileException() throw() {}
or just inherit from std::runtime_error instead of std::exception, which has a constructor that takes std::string input.
Simplify with:
// Derive from std::runtime_error rather than std::exception
// std::runtime_error (unlike std::exception) accepts a string as an argument that will
// be used as the error message.
//
// Note: Some versions of MSVC have a non standard std::exception that accepts a string
//       Do not rely on this.
class FileException : public std::runtime_error
{
public:
    // Pass error msg by const reference.
    FileException(std::string const& error)
        // Pass the error to the standard exception
        : std::runtime_error(error)
    {}
    // what() is defined in std::runtime_error to do what is correct
};
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With