在c++中捕获const char*异常



我为我的程序做了一个例外:

class PortNotDefined: public exception
{
public:
const char* what() const throw()
{
    return "Puerto no definido o no disponible";
}
} PortNotDefined;

后来,我使用了这样一个try-catch块:

try{.....}
catch(const char* a){
    std::string error(a);
    ...
}

但它没有捕获异常,我不知道我是否定义好了异常,或者在尝试捕获时有问题

感谢您抽出时间^^

首先,您的异常类型为PortNotDefined,因此您应该使用catch(const PortNotDefined& d)进行捕获,而不是捕获(const char*a)。返回constchar*不会使其成为constchar*异常。

其次,在您的try块中,需要抛出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;
    }
}

或者一般情况下,您可以捕获std::exception的const-ref,这是继承层次结构的原因。

catch(const std::exception& ex)

catch(const char* a)将捕获类型为const char*的对象。如果抛出类型为PortNotDefined的对象,则需要捕获该类型的catch子句,通常为catch(PortNotDefined d)catch(const PortNotDefined& d)

最新更新