如何派生自定义的exception?
CException派生自exception
CException::CException(const char* lpszFormat, ...)
{
va_list argList;
va_start(argList, lpszFormat);
char ctmp[MAX_EXCEPTION_LONGTH];
vsprintf(ctmp,lpszFormat,argList);
va_end(argList);
std::exception::exception(ctmp);
}
本来想支持可变参数,
但是为什么
try
{
throw new CException( "def ");
}
catch (jks::CException* e)
{
cout < <e-> what();
}
还是Unknow exception????????????
[解决办法]
throw new CException( "def "); ??
throw CException( "def ");这样写的吧
[解决办法]
std::exception::exception(ctmp);
你这一行没作用的,这只是定义一个std::exception类的临时对象,不是初始化父类子对象。初始化父类子对象只能在构造函数的初始化列表中进行。
[解决办法]
#include <iostream>
#include <cstdarg>
#include <stdexcept>
using namespace std;
const int MAX_EXCEPTION_LONGTH = 255;
class CException:public exception
{
public:
CException(const char* format, ...);
private:
static string MakeExceptionStr(const char*& format);
};
CException::CException(const char* format, ...)
:exception(MakeExceptionStr(format).c_str())
{
}
string CException::MakeExceptionStr(const char*& format)
{
va_list argList;
va_start(argList, format);
char ctmp[MAX_EXCEPTION_LONGTH];
vsprintf(ctmp,format,argList);
va_end(argList);
return string(ctmp);
}
//test
int main()
{
try
{
throw CException( "No.%d exception %s ", 11, "happened ");
}
catch (CException& e)
{
cout < <e.what();
}
cout < <endl;
system( "pause ");
}
[解决办法]
赞同lightnut()的方案
怎么派生自定义的exception
如何派生自定义的exception?CException派生自exceptionCException::CException(constchar*lpszFormat,...)
