Throwing exception when array is out of bounds
c++
Solution
Go with your `MatrixRow` solution, but pass the index of the row to each `MatrixRow` as a constructor argument. The `MatrixRow` can save that number, and use it in any exception messages it generates.
Problem
I have a matrix class, that uses [][] to access elements. When one (or both) indexes are out of bounds, I have to throw CIndexException. It's a class that stores text in this format "Invalid index [a][b]", where a and b are numbers. This is my current implementation of CIndexException class ``` class CIndexException { string text; public: CIndexException (int a, int b) { ostringstream oss; oss << "Invalid index ["; oss << a; oss << "]["; oss << b; oss < "]"; text = oss.str(); } string get() const { return text; } }; ``` Matrix is represented as a 2D array of doubles, it is initialized in constructor: ``` CMatrix(int r, int c) { colls = c; rows = r; mat = new double * [rows]; for (int i = 0; i < rows; i++) { mat[i] = new double [colls]; for (int j = 0; j < colls; j++) mat[i][j] = 0; } } ``` To get single element, I overloaded [] operator like this: ``` double * operator[] (int x) const { return mat[x]; } ``` When I type a[2][3], this function resolves the first [], returns pointer to an array and the second [] gets resolved as usual. I can easily check if the first index is out of bounds, but I have trouble checking for the second one. I thought of creating second class, MatrixRow, that represents one row of matrix. Then I would have array of MatrixRows. To get [][] working, both of those classes would have overloaded operator[]. That way I would be able to check both indexes, but I have no idea how to "join" them into one exception. How can I report both indices in the exception object while using this design?