Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a typical pattern for handling wide character strings in exceptions?

Tags:

c++

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....

like image 734
Billy ONeal Avatar asked Dec 17 '10 07:12

Billy ONeal


2 Answers

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.

like image 156
Jörgen Sigvardsson Avatar answered Oct 20 '22 00:10

Jörgen Sigvardsson


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.

like image 35
Abyx Avatar answered Oct 19 '22 23:10

Abyx