c++ - Unicode exception class -
i want implement header-only class unicode exception , i've started following code:
#pragma once #include <string> #include <exception> using namespace std; class uexception : public exception { public: explicit uexception(const wchar_t* msg) { this->msg = msg; } explicit uexception(const wstring& msg) { this->msg = msg; } const wchar_t* uwhat() const throw () { return msg.c_str(); } private: wstring msg; const char* what() const throw () //hidden { return null; } };
this works fine, have questions:
- why need derive std::exception class? may not needed @ all?
- am miss in class implementation?
you don't have inherit
std::exception
. inheriting directly, or indirectly has advantage of allowing users of interface catch exception referencestd::exception
- without depending on definition of exception type.of course, accessing
uwhat
won't possible throughstd::exception
anyway, if don't intend implement suggestion†, not inheritingstd::exception
might desirable design.if decide inherit, reducing visibility of
what
not possible. ††your implementation of
what
violates interface ofstd::exception
not returning pointer null terminated string. if exception handler catches referencestd::exception
, callswhat()
, dereferences pointer, chaos ensue.a trivial way implement
what
return ""
instead. however... †
† recommend considering alternative: instead of returning "nothing", convert encoding of stored wide string native narrow string enconding , return pointer that. sure, lot more work implement, make exception more convenient.
†† technically can reduce visibility of uexception::what
, have not affect visibility of uexception::exception::what
. besides, doing violates liskov substitution principle. recommend either inherit std::exception
, implement what
publicly , properly, or don't inherit std::exception
@ all.
Comments
Post a Comment