1

I tried to figure out how to implement my own base class for C++ exceptions which allow adding an error specific text string. I see no possibility for the std::c++ exceptions to change the error text, even not in C++11: http://www.cplusplus.com/reference/exception/exception/. I also want to derive more specific exceptions from my Exception-base class. I read a lot of articles but I am still unsure whether my following implementation covers all important aspects.

class Exception : public std::exception {      
    public:
        Exception(const char* message) : m(message) {

        }

        virtual ~Exception() throw() {

        }

        virtual const char* what() const throw() {
            return m.c_str();
        }

    protected:
        std::string m;

    private:
        Exception();
    };

Is this implementation fine?

3

1 Answer 1

3

If you derive from runtime_error (and your compiler supports inheriting constructors) you can condense your class to

struct Exception : public std::runtime_error
{
  using runtime_error::runtime_error;
};

throw(): Exception specifications are deprecated as of C++11, use noexcept instead.

Sign up to request clarification or add additional context in comments.

2 Comments

And what if you want to throw a logic_error from time to time?
My point is, for a generic Exception base class like requested by the question, it seems odd to suggest deriving from std::runtime_error, which only represents a small subset of the possible error cases. This could complicate writing reasonable catch statements on the user side later.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.