I suggest that you #include <stdexcept> and write it in this way:
Code:
string getVal(const vector<vector<string>>& matrix, int row, int col)
{
// account for offsets
--row;
--col;
// make sure it is within bound
if (row < 0 || col < 0 || col >= cols || row >= rows)
{
throw out_of_range("Out of Bounds Error!");
}
return matrix[row][col];
}
Now, to call it would be something like this:
Code:
try
{
string str = getVal(matrix, row, col);
// ...
}
catch (const out_of_range& ex)
{
cout << "\n*** " << ex.what() << " ***" << endl;
}
Originally Posted by
Mirage
I've added a return NULL; right after the print statement but this opens up a new problem
That is not really correct. You might return an empty string, but not NULL, which is zero. The point of my example is that I don't have to cater for this, because if the arguments are out of range, the exception is throw, rather than thrown and then caught at the same place, leading to a path of control where nothing is returned despite the return type not being void.