Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Exception:Throwing Arrays and getting array size in catch

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

like image 930
Sree Avatar asked May 06 '15 06:05

Sree


1 Answers

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)
{
...
}
like image 189
MSH Avatar answered Sep 29 '22 11:09

MSH