I have written an open source and cross-platform C++ File Library which have exception and error codes. Exceptions can be disabled when the program is running. In that case, the user have to check the error codes. Of course, when exception throwing is enabled, error code won't be returned because exception is thrown before the called function returns.
Currently, exceptions still could be thrown when disabled (bug). I'll fix that soon. Someone comment to me that it is considered bad design to have both exception and error codes. I agree with him and I am about to remove the error codes and have library throw custom derived exceptions with more error information.
But I hesitate. I like to have this hybrid approach for performance reasons. This is what I am thinking of doing: keeping exception throwing and error codes but exception throwing is disabled through macro at compile time instead of runtime.
If user define the following in a common config file
#define ELMAX_EXCEPTION 1
The follow code
int Write(std::wstring str) ELMAX_THROW_OR_NOT;
would expand to either of the 2.
// under C++11 compiler int Write(std::wstring str) noexcept; // under C++98 compiler int Write(std::wstring str) throw();
ELMAX_EXCEPTION is not defined or is zero, the macro would expand to nothing.
int Write(std::wstring) ;
The reason I want to do this, is for library user who wants the performance gain of not having the compiler generating the stack unwinding code (for exception) and compiler can better optimize such functions. My C++ file library is using C file API and the only thing which could throw exception is
new keyword, which I intend to add
nothrow. The UTF-8 code can also throw exceptions (need to be changed too)
char *parr = new (nothrow) char[num]; if(parr==NULL) // handle it either through error code or throw exception (if enabled)
Please kindly advise if I should have a pure exception approach or a hybrid approach (as mentioned), for my library errors?