-2

First of all, I did indeed do a quick search on google, and none of it explained what I am shooting for.

Edit: For instance, I looked here.

The class std::runtime_error is an exception class that signals an error that occurs at runtime. Unless I'm mistaken, it has no default constructor (I got an error when trying to derive from it without explicitly calling a parent constructor) but it does have string(-ish) constructors that allow you to specify a message.

My question is how would you access that message in a member function such as what() (virtual function in std::exception)? There is no getMessage() or similar function defined in the parent class, and calling what() is rather useless if that happens to be the function I am overriding.

I am using Visual Studio Community 2015, so a compiler-specific method is okay, but I would prefer a portable solution.

2
  • "calling what() is rather useless if that happens to be the function I am overriding." What do you mean? Commented Jan 21, 2017 at 19:52
  • I assume, this question is your answer Commented Jan 21, 2017 at 20:31

1 Answer 1

3

Specify that you want the base class's what instead of your own:

const char* what() const noexcept override {
    auto base_msg = std::runtime_error::what();
    return /* something using base_msg */;
}

However, there's not much you can really do in what while keeping true to const and noexcept, and also returning a pointer to data that will outlive the function call. You can do formatting in the constructor and return a buffer your class contains. Just be aware that the last thing you want while trying to throw an exception is another error.

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

1 Comment

[[nodiscard]] is missing. =)

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.