Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;异常:在catch中抛出数组并获取数组大小_C++_Arrays_Exception Handling - Fatal编程技术网

C++ C++;异常:在catch中抛出数组并获取数组大小

C++ C++;异常:在catch中抛出数组并获取数组大小,c++,arrays,exception-handling,C++,Arrays,Exception Handling,普通函数(比如printArray)使用数组及其大小(2个参数)来打印数组的元素 如何使用异常执行相同的操作?更确切地说,如何将数组大小传递给catch处理程序?(假设我没有在try catch之外声明const int SIZE) 例如 提前感谢您您可以按以下方式将阵列及其大小成对抛出: throw std::make_pair(foo, 5); 得到如下两个值: catch(std::pair<int*, int>& ex) { ... } catch(std::pa

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

如何使用异常执行相同的操作?更确切地说,如何将数组大小传递给catch处理程序?(假设我没有在try catch之外声明const int SIZE) 例如


提前感谢您

您可以按以下方式将阵列及其大小成对抛出:

throw std::make_pair(foo, 5);
得到如下两个值:

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

谢谢大家的评论。pair示例有效(可能在堆上使用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;
}
intmain()
{
int foo[]={16,2,77,40,12071};
int size=sizeof(foo)/sizeof(int);
试一试{
//扔福;
投掷(成对(foo,大小));
}
捕获(int*foo)
{
对于(int i=0;i如果函数接受数组,为什么要在try块内部初始化它呢?int foo[]={16,2,77,40,12071};抛出一个
std::vector
@Ashot-对不起,假设int foo[]={16,2,77,40,12071};在尝试之前位于行中{。我编辑了上面的代码。谢谢杰瑞,是的,向量确实有效,但我很想知道是否可以使用基本C++的数组来获得数组大小,如果catch处理程序在另一个函数中,而数组是本地非静态变量,那么栈解卷将在到达处理程序之前破坏数组。如果数组在同一个函数中,您应该知道大小。在
catch
中,您需要尖括号。您还需要记住,确定固定数组大小的一种典型方法是通过
sizeof foo/sizeof*foo
。当用作
std::make_pair
的第二个参数时,将不会是
int
,因此不合格如果数组是在try块中声明的,那么无论如何也不能用该指针做任何事情。
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;
}