【问题标题】:C++ Exception:Throwing Arrays and getting array size in catchC++ 异常:抛出数组并获取数组大小
【发布时间】:2015-07-16 03:44:16
【问题描述】:

普通函数(比如 printArray)采用数组及其大小(2 个参数)来打印数组的元素。

如何使用异常来做同样的事情?更准确地说,如何将数组大小传递给 catch 处理程序? (假设我没有在 try-catch 之外声明 const int SIZE) 例如。

 //void printArray(int* foo ,int size);
     int foo[] = { 16, 2, 77, 40, 12071 };
   //printArray(foo,5); //OK, function call using array accepts size=5 
    try{

        //do something
        throw foo;

    }
    catch (int* pa)
    {
        //I have to get array size to loop through and print array values
        //    How to get array size?
    }

提前谢谢你

【问题讨论】:

  • 如果函数需要数组,为什么在 try 块中你初始化了它? int foo[] = { 16, 2, 77, 40, 12071 };
  • 投一个std::vector
  • @Ashot - 抱歉,假设 int foo[] = { 16, 2, 77, 40, 12071 };在尝试 {.我在上面编辑了代码。谢谢杰瑞,是的向量确实有效,但我很想知道是否可以使用基本的 c++ 数组来获取数组大小
  • 请注意,如果 catch 处理程序位于数组之外的另一个函数中,并且数组是本地非静态变量,则堆栈展开将在您到达处理程序之前破坏数组。如果数组在同一个函数中,无论如何你都应该知道大小。

标签: c++ arrays exception-handling


【解决方案1】:

您可以通过以下方式将数组及其大小作为一对抛出:

throw std::make_pair(foo, 5);

并像这样获取这两个值:

catch(std::pair<int*, int>& ex)
{
...
}

【讨论】:

  • catch 中需要尖括号。
  • 您还需要记住确定固定数组大小的典型方法是通过sizeof foo/sizeof *foo。当用作std::make_pair 的第二个参数时,将int,因此不符合您的捕获条件。并不是说如果在 try 块中声明了数组,那么无论如何您都可以使用该指针做任何事情。
【解决方案2】:

感谢大家的cmets。对示例有效(在堆上使用 arr 时可能会使用,并且在抛出时会在调用函数时捕获)。 celtschk ref,非常有帮助。我会将此信息用于同一范围内的本地非静态数组

int main()
{
    int foo[] = { 16, 2, 77, 40, 12071 };
    int size = sizeof(foo)/ sizeof(int);
    try{
        //throw foo;
        throw (pair<int*,int>(foo,size));
    }
    catch (int* foo)
    {
        for (int i = 0; i < size; i++)
            cout << foo[i] << ",";
    }
    catch (pair<int*, int>& ip)
    {
        cout << "pair.." << endl;
        for (int i = 0; i < ip.second; i++)
            cout << ip.first[i] << ",";
    }
    cout << endl;
}

【讨论】:

    猜你喜欢
    • 2019-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-24
    • 2020-07-29
    • 2020-11-11
    相关资源
    最近更新 更多