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



>问题

我有一个 GLSLFailedToLoadException,它派生自异常类 GlHelperException。

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

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

异常定义


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__

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

更改 throw 语句以抛出对象:

throw GLSLFailedToLoadException(__FILE__, __LINE__);

我还建议始终通过const引用来catch例外,因此:

catch (const GLSLFailedToLoadException& e)

由于您的代码当前是编写的,因此您无法捕获异常,因此它会留下main(),从而导致您看到的结果 - 一个未捕获的异常终止程序。

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

最新更新