我为我的程序做了一个异常(exception):
class PortNotDefined: public exception
{
public:
const char* what() const throw()
{
return "Puerto no definido o no disponible";
}
} PortNotDefined;
然后,我使用这样的 try-catch block :
try{.....}
catch(const char* a){
std::string error(a);
...
}
但是没有捕捉到异常,不知道是我定义的异常还是try-catch的问题
感谢您的宝贵时间^^
最佳答案
首先,您的异常属于 PortNotDefined 类型,因此您应该使用 catch(const PortNotDefined& d)
而不是 catch(const char* a) 进行捕获。返回 const char* 不会使其成为 const char* 异常。
其次,在您的 try block 中需要抛出 PortNotDefined。否则,异常将永远不会被捕获,因为它从未被抛出。
第三,我认为您在声明异常类时存在语法错误。这是一个完整的有效示例:
class PortNotDefined: public exception
{
public:
const char* what() const throw()
{
return "Puerto no definido o no disponible";
}
};
void methodThatWillThrowPortNotDefined ()
{
throw PortNotDefined();
}
void test()
{
try{
methodThatWillThrowPortNotDefined();
}
catch(const PortNotDefined& pnd){
std::string error(pnd.what());
cerr << "Exception:" << error << endl;
}
}
关于c++ - 在 C++ 中捕获 const char* 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18144355/