捕获块调试语句在引发异常后未执行
Catch Block Debug Statement not executing after an exception is thrown?
>问题
我有一个 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 *
(,因为您当前存储的指针在对象的持续时间内不会存在,因此您需要复制指向字符串。
相关文章:
- Firebase C++VS2018 SDL2-在Firebase::app::create(..)上执行异常处理
- 捕获异常后如何退出程序执行
- 如何处理libstdc++跨执行边界抛出的异常
- 主函数执行时C++堆栈溢出异常
- 英特尔 Pin:RECEIVED_ACCESS_FAULT异常后正确继续执行
- PAGE_GUARD,VirtualProtect不会在执行访问时引发异常
- 执行视觉工作室异常处理模式
- C++执行期间的类成员函数错误/异常处理
- 在 Arraydeque 中设置异常不会停止执行
- 我在执行 levelOrder 函数时无法弄清楚异常终止的原因?
- 通过引用派生类对象从基类对象执行向下转换时引发bad_cast异常
- 捕获块调试语句在引发异常后未执行
- G++ 和 CL(VS2017) 都编译成功,但 cl 编译的可执行文件运行异常
- 在机器异常之后重新执行程序
- 异常的奇怪行为(执行了一些未调用的方法)
- 自定义异常并不总是执行 what()
- 在std::for_each的执行过程中累积结果,该异常被中断
- 在堆栈中执行 POP 时在下溢中进行异常处理
- 给定范围内的完美平方:循环执行异常
- 当我们不给 C 可执行程序参数时如何处理异常