C++ : how to return the value from an out of bounds array with exception handling?
<p>I am having trouble returning the value of an out of bounds array using an exception formalism.</p>

<p>I create an array object in my main script with for example length 10 using a class Array. Than I try to set the 11th element of the array to a certain value. In my class Array I throw back a value from a class ArrayOutOfBounds when the index of an array is larger than the size of the array, which is true in this case. In my main script I than catch this object from the ArrayOutofBounds class to give the out of bounds index and a terminal message that states that the array is out of bounds. However, how do I return the actual value I was trying to set the 11th element to?</p>

<p>It looks as follows:</p>

<p>class ArrayOutOfBounds + overloading operator &lt;&lt; function</p>

<pre><code>class ArrayOutOfBounds {
public:

ArrayOutOfBounds(int index) : _index(index) {} ;

int index() const { return _index ; }

private:
int _index ;
} ;

ostream&amp; operator&lt;&lt;(ostream&amp; os,const ArrayOutOfBounds&amp; m) {
  return (os &lt;&lt; "Array index is out of bounds") ;
}
</code></pre>

<p>Throw back function within class Array:</p>

<pre><code>double&amp; operator[](int index) {
if(index &gt; _size) {
    ArrayOutOfBounds aoob(index) ;
    throw aoob ;        
}
return _arr[index] ;
</code></pre>

<p>Main script:</p>

<pre><code>int main() {

Array array(10) ;

try {
    array[11] = 10 ;
}

catch(ArrayOutOfBounds aoob) {
    cout &lt;&lt; '\n' ;
    cout &lt;&lt; aoob &lt;&lt; " (index, value): " &lt;&lt; aoob.index() &lt;&lt; ", " &lt;&lt; 10 &lt;&lt; endl ;
}

cout &lt;&lt; '\n' ;
return 0 ;
}
</code></pre>

<p>I tried to add a second throw value that throws _arr[index] but I understood you can't throw two things at once.</p>