Reputation: 347
A Normal function ( say printArray) takes array and its size ( 2 arguments ) to print elements of an array.
How to do the same using exceptions? More exactly, how to pass array size to catch handler ? ( assuming I dont have a const int SIZE declared outside try-catch) eg.
//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?
}
Thank you in advance
Upvotes: 5
Views: 3176
Reputation: 347
Thank you all for the comments. pair example works ( probably will use when using arr on heap, and when thrown , caught on calling function ). celtschk ref, was very helpful . I will use this info for local non static array on same scope
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;
}
Upvotes: 0
Reputation: 417
You can throw both array and it's size as a pair in the following way:
throw std::make_pair(foo, 5);
and get these two values like this:
catch(std::pair<int*, int>& ex)
{
...
}
Upvotes: 6