Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::exception subclass, string member variable

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

like image 235
alex Avatar asked Dec 23 '11 16:12

alex


2 Answers

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.

like image 77
kennytm Avatar answered Sep 26 '22 21:09

kennytm


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
};
like image 30
Martin York Avatar answered Sep 22 '22 21:09

Martin York