[SOLVED] Passing message in std::exception from managed code to unmanaged


I am trying to throw a std::exception from managed code so that it is caught in unmanaged code. Where I’m struggling is passing a string (describing the exception) so that the (re-)caught exception can be examined using the what() method …

#pragma managed

static std::string InvokeMethod() {

    try {
    catch (Exception^ ex) {
      std::string myExMsg = msclr::interop::marshal_as<std::string>(ex->ToString());
      throw std::exception(myExMsg);
#pragma unmanaged

   void Execute() {
      try {
        myMethod = InvokeMethod();
      catch (std::exception ex) {

This doesn’t compile with "no instance of constructor "stdext:exceptipon::exception" matches the argument list argument types are (std::string)" BUT if I ‘hard code’ a string into std::exception like this …

 throw std::exception("An error has occurred");

… then that string gets passed along and returned by ex.what(). I also tried …

throw std::runtime_error(myExMsg);

… but ex.what() just returns a string ending with ‘\x7F’ (in case that’s a clue).

It looks to me that std::exception is expecting some other type. But what type? What does ‘myExMsg’ need to be so that ex.what() returns the same string (that can be used in the SetError method)?


Following suggestion made by @Joe, I inherit from std::exception …

 class InvokeException : public std::exception {
    InvokeException(std::string const& message) : msg_(message) { }
    virtual char const* what() const noexcept { return msg_.c_str(); }

    std::string msg_;

… and then …

const std::string myExMsg = msclr::interop::marshal_as<std::string>(ex->Message);
throw InvokeException(myExMsg);

Answered By – Alex M

Answer Checked By – Cary Denson (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *