【发布时间】:2019-04-06 16:27:46
【问题描述】:
问题
我有一个派生自异常类 GlHelperException 的 GLSLFailedToLoadException。
GlHelperException 具有虚拟 throw 函数,以异常的标题属性和文件名的行号来描述错误。
但是当我在 main 函数中测试异常时,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__
【问题讨论】:
-
在您的
GLSLFailedToLoadException构造函数中,您真的 应该使用初始化列表而不是构造函数主体。然后将您的const char *成员更改为const std::strings,这样您就可以真正复制传入的值,而不仅仅是存储即将失效的指针。