嵌套尝试捕获 C++ 中的问题
nested try catch Issues in c++
我在 C++ 中嵌套的 try-catch 块时遇到问题,
它没有完美地传递值(指针,也许范围是原因),在外部 try-catch 块中为 null
try{
try{
string e
...
throw e.c_str();
}
catch(const char *a){
throw a; // I had also tried taking 'a' into another string object and then throwed it but it didn't work
}
}
catch(const char *a){
cout<<a<<endl;
}
当你在内部try
块中抛出异常时,e
string
在堆栈展开过程中被销毁,指向其缓冲区的指针不再指向有效的内存位置。
一般规则是:按值抛出,按引用捕获。
try
{
try
{
string e
...
throw e;
}
catch(string & a)
{
throw a;
}
}
catch(string & a)
{
cout << a << endl;
}
结果:https://ideone.com/nY0FYM
您正在返回指向std::string
本地对象的内部缓冲区的指针。当 catch 块进入范围时,该对象不再存在。您应该抛出字符串对象,而不是其内部缓冲区。
当抛出异常时,自 Enter 到try{}
块到异常发生点以来在堆栈上分配的所有变量都将作为称为堆栈展开的过程的一部分被销毁。因此,catch()
中的指针指向已释放的内存。您可以通过按值抛出来避免这种情况,以便将值复制到要抛出的异常对象。
string
超出了范围,因此char const *
指向狂野。要解决此问题,您可以抛出 std::exception
的导数(它将字符串作为构造函数参数),但捕获一个std::exception &
。然后创建一个包含该字符串的异常对象,一切都很好。
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 编译包含字符串的代码时遇到问题
- Project Euler问题4的错误解决方案
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 静态数据成员的问题-修复链接错误会导致编译器错误
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 一个关于在C++中重载布尔运算符的问题
- 首要问题的答案让值班员搞错了
- setlocale的C++土耳其字符串问题
- 如何重构类层次结构以避免菱形问题
- 基于boost的程序的静态链接——zlib问题
- C++格式化输出问题
- 使用mongocxx驱动程序时包含头文件问题