嵌套尝试捕获 C++ 中的问题

nested try catch Issues in c++

本文关键字:问题 C++ 嵌套      更新时间:2023-10-16

我在 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 &。然后创建一个包含该字符串的异常对象,一切都很好。