C ++ exception: Throwing arrays and getting array size in catch

A normal function (e.g. printArray) takes an array and its size (2 arguments) to print the elements of the array.

How to do the same using exceptions? More precisely, how to pass the size of the array to the catch handler? (assuming I don't have a const int SIZE declared outside of try-catch) for example.

//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

+5
source share
2 answers

You can throw away both the array and its size as a pair as follows:

 throw std::make_pair(foo, 5); 

and get the following two values:

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

Thanks everyone for the comments. (It will probably be used when using arr on the heap, as well as when throwing when calling a function). celtschk ref, was very helpful. I will use this information for a local non-static array in the same area

 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; } 
0
source

All Articles