afarley
afarley

Reputation: 815

Why doesn't the VS Test Explorer show my C++ custom exception message?

I've implemented a custom exception in my C++ code:

class LicenseFileNotPresent : public std::exception
{
private:
    std::string message = "license.json not found in %APPDATA/XXX/ or file is not populated.";
public:
    const char* what() const noexcept override
    {
        return message.c_str();
    }
};

However, when I run a test using VS2019's Test Explorer, and this exception is thrown (by a unit test which is not intended to cause this exception), I get an unhelpful result:

Message: Unhandled C++ Exception

I expected that this message would instead read:

Message: license.json not found in %APPDATA/XXX/ or file is not populated.

I've read a few other posts which don't answer my question:
C++ custom exception message not displaying
How can I show a custom exception message in visual studio test explorer

  1. I'm not returning a string that goes out of scope after the what() function returns
  2. I'm not trying to test this exception in this case, so a try/catch is not what I'm looking for.

Upvotes: 1

Views: 270

Answers (1)

afarley
afarley

Reputation: 815

The issue turned out to be my mistaken assumptions about where the VS test framework gets the message "Unhandled C++ Exception". I was thinking that the test executor would dive into the std::exception object to get the what() message, but this is not safe behavior on the part of the test framework because it can't be sure that I'm throwing a std::exception versus other possibilities.

The reason so many comments say things like "where is your try/catch block?" is that this is the only way to run unit tests that may throw exceptions, even if the exception is not expected to be thrown by the test!

Thanks to @queztalcoatl for the complete explanation given in the comments.

Upvotes: 1

Related Questions