我尝试做出自己的例外,即可以使用一个或两个参数抛出该异常。所以我要做的就是重载异常的构造函数。但是,似乎没有调用第二个构造函数。这是我的代码:
代码清单1。
class myException: public std::exception {
public:
/*
* first constructor
*/
myException(unsigned short ExceptionCode):exception(){
code = ExceptionCode;
errorMessage = std::string("");
}
/*
* second constructor
*/
myException(unsigned short ExceptionCode, std::string errorMessage):exception(){
std::cout << "debugging message";//present here for debugging purpose only
code = ExceptionCode;
this->errorMessage = errorMessage;
}
const char * what() const throw ()
{
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.c_str();
}
~myException() throw(){}
private:
std::string errorMessage;
unsigned short code;
};
例如,当我这样称呼它时:
代码清单2。
void myFunction(myClass myObject){
//some code
if(conditionsMeet)
throw myException(MYERROR_CODE_2,"this is a more specific custom message for code 2");
//some other code
}
“调试消息”根本没有出现。当我评论“第一个构造函数”时,我得到一个错误和很多警告。
错误清单1。
main.cpp:28:41: error: no matching function for call to 'myException::myException(ExceptionCode)'
throw myException(MYERROR_CODE_2);
^
main.cpp:28:41: note: candidates are:
In file included from Node.h:12:0,
from main.cpp:10:
myException.h:50:5: note: myException::myException(short unsigned int, std::string)
myException(unsigned short ExceptionCode, std::string errorMessage):exception(){
^
myException.h:50:5: note: candidate expects 2 arguments, 1 provided
myException.h:44:7: note: myException::myException(const myException&)
class myException: public std::exception {
^
myException.h:44:7: note: no known conversion for argument 1 from 'ExceptionCode' to 'const myException&'
编辑:错误代码定义如下:
代码清单2。
enum ExceptionCode{
MYERROR_CODE_1 = 1,
MYERROR_CODE_2 = 2,
};
谁能向我解释我做错了什么,为什么?提前致谢。
正如Massa所指出的,由于示例行而不会引发您得到的编译错误:
throw myException(MYERROR_CODE_2,"this is a more specific custom message for code 2");
而是因为您在代码的其他位置调用了第一个构造函数,例如:
throw myException(MYERROR_CODE_2);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句