Standard C++'s std::exception::what()
returns a narrow character string. Therefore, if I want to put a wide character string message there, I can't.
Is there a common way/pattern/library of/for getting around this?
EDIT: To be clear, I could just write my own exception class and inherit from it -- but I'm curious if there's a more or less standard implementation of this. boost::exception
seems to do most of what I was thinking of....
Based on this post Exceptions with Unicode what(), I decided to do something like this:
class uexception : public std::exception {
public:
uexception(LPCTSTR lpszMessage)
: std::exception(TCharToUtf8(lpszMessage)) { }
};
Everywhere in my code base, I am assuming that .what()
will return a string that is encoded in UTF-8. My conversion routines from UTF-8 to TCHAR
will skip unrecognized UTF-8 sequences, and replace them with ?. That way, if .what()
returns something that isn't valid UTF-8, it won't be an epic fail.
The code has not been compiled (later today - have to fix some other things first! :). I also apologize for the MFC-isms in there, but I think the message gets across anyway.
You can put anything there, but if third-party code expects a const char*
from what()
, you should return const char*
from it.
For your code - just derive from std::exception
and add const wchar_t* wwhat()
method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With