引发异常后,捕获块调试语句未执行?

时间:2019-04-06 16:27:46

标签: c++ linux c++11 g++

问题

我有一个从异常类GlHelperException派生的GLSLFailedToLoadException。

GlHelperException具有虚拟throw函数,用于使用异常的title属性和带有文件名的行号来描述错误。

但是,当我在主函数中测试异常时,catch块未打印正确的what()函数调试日志,并在抛出GLSLFailtedToLoadException实例后返回调用终止。

异常定义


class GlHelperException: public std::exception{
public:
    virtual const char* what() const throw(){
        return (std::string(this->title) + 
        " - in file " + 
        std::string(this->filename) + 
        " at line " + 
        std::to_string(this->line)).c_str();    
    }

protected:

    const char *title;
    const char *filename;
    int line;
};


class GLSLFailedToLoadException: public GlHelperException{
public:
    GLSLFailedToLoadException(const char *filename, int line);
};


GLSLFailedToLoadException::GLSLFailedToLoadException(const char *filename, int line){
    this->filename = filename;
    this->line = line;
    this->title = "Failed to load and compile GLSL program ";
}

测试投掷站点



int main(int argc, char **argv){
/* Irrelevant Code*/

    try{
        throw new GLSLFailedToLoadException(__FILE__, __LINE__);
    }
    catch(GLSLFailedToLoadException &e){
        std::cout<<"Exception Caught"<<std::endl;
        std::cout<<e.what()<<std::endl;
    }
    return 0;
}

实际结果

terminate called after throwing an instance of 'GLSLFailedToLoadException*'
Aborted (core dumped)

预期结果

Failed to load and compile GLSL program in __FILE__ at __LINE__

1 个答案:

答案 0 :(得分:2)

您正在抛出一个指向对象的指针,但是试图捕获一个对象(通过引用)。

更改您的throw语句以引发对象:

throw GLSLFailedToLoadException(__FILE__, __LINE__);

我还建议始终通过catch参考引用const个异常,因此:

catch (const GLSLFailedToLoadException& e)

当前正在编写代码时,您无法捕获该异常,因此它离开了main(),导致看到的结果是未捕获的异常终止了程序。

您还需要在异常对象中使用std::string而不是指针(const char *),因为当前存储的指针在对象持续时间内不存在,因此您需要指向字符串的副本。

相关问题