我尝试创建自己的异常,我可以使用一个或两个参数抛出该异常。所以我所做的就是重载异常的构造函数。然而,第二个构造函数似乎没有被调用。这是我的代码:
code-listing-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;
};
例如,当我这样调用它时:
code-listing-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
}
“调试消息”根本没有出现。当我评论“第一个构造函数”时,我得到一个错误和很多警告。
error-listing-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&'
编辑:错误代码定义如下:
代码 list 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);
关于C++异常重载构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23567363/