5

I need my exception class, that inherits runtime_class, to accept wstring&. This is MyExceptions.h:

using namespace std;

class myExceptions : public runtime_error
{

public:
    myExceptions(const string &msg ) : runtime_error(msg){};
    ~myExceptions() throw(){};

};

I would like myExceptions to accept wstring& like this : myExceptions(const **wstring** &msg ). But when I run that, I got this error:

C2664: 'std::runtime_error(const std__string &): cannot convert parameter 1 from 'const std::wstring' to 'const std::string &'

I understand that runtime_error accepts string& and not wstring& as defined as following from C++ Reference - runtime_error:

> explicit runtime_error (const string& what_arg); 

How can I use wstring& with in runtime_error?

Keith Pinson
  • 7,835
  • 7
  • 61
  • 104
Colet
  • 495
  • 2
  • 8
  • 22
  • how about writing another constructor taking wstring as parameters? – taocp Mar 13 '14 at 14:21
  • 1
    Minor clarification: that's a compile error, it just happens to have the words runtime in the error message. – Chris O Mar 13 '14 at 14:36
  • I thought so, but I don't know how to do it. I should overwrite it in this way? explicit runtime_error(const wstring& msg); and where? in MyExceptions.h class? – Colet Mar 13 '14 at 14:52

1 Answers1

3

The easiest thing to do would be to pass to runtime_error a conventional message and handle your wstring message directly in your myExceptions class:

class myExceptions : public runtime_error {
public:
    myExceptions(const wstring &msg ) : runtime_error("Error!"), message(msg) {};
    ~myExceptions() throw(){};

    wstring get_message() { return message; }

private:
    wstring message;
};

Otherwise you could write a private static member function that converted from wstring to string and use it to pass the converted string to runtime_error's constructor. However, as you can see from this answer, it's not a very simple thing to do, possibly a bit too much for an exception constructor.

Community
  • 1
  • 1
Nicola Musatti
  • 17,834
  • 2
  • 46
  • 55