Taking your example and providing definitions for the error codes, all compiles.
However, there is a serious bug in the what() function which will cause a crash one day.
You are calling c_str() on a temporary and then returning the pointer to memory that has now been freed. This is very very bad.
You need to store the string in the exception and build it during the constructor to be safe.
example provided:
#include <iostream>
#include <exception>
enum Errors {
MYERROR_CODE_1,
MYERROR_CODE_2
};
class myException: public std::exception {
public:
/*
* only one constructor necessary
*/
myException(unsigned short ExceptionCode, std::string errorMessage = std::string())
: exception()
, message(buildErrorMessage(ExceptionCode, errorMessage))
, code(ExceptionCode)
{
std::cout << "debugging message\n";//present here for debugging purpose only
}
static std::string buildErrorMessage(unsigned short code, const std::string& errorMessage) {
std::string tmp;
switch(code){
case MYERROR_CODE_1:
tmp = std::string("MYERROR_CODE_1 : ");
if(errorMessage.empty())
tmp += std::string("this is a default error message for code 1");
tmp += errorMessage;
break;
case MYERROR_CODE_2:
tmp = std::string("MYERROR_CODE_2 : ");
if(errorMessage.empty())
tmp += std::string("this is a default error message for code 2");
tmp += errorMessage;
}
return tmp;
}
const char * what() const throw ()
{
return message.c_str();
}
private:
std::string message;
unsigned short code;
};
using namespace std;
int main()
{
int err = MYERROR_CODE_1;
try {
throw myException(err);
}
catch(exception& e) {
cout << e.what() << endl;
}
try
{
throw myException(err, "more info");
}
catch(exception& e) {
cout << e.what() << endl;
}
}