I'm trying to make a 2D array class so I can deal with them more easily, by creating a dynamically allocated a 1D array. I've gotten up to writing the () operator, but I'm not sure what I should do if the row / column is out of bounds. How should I treat this? Should I throw an exception? Or something else?
1 2 3 4 5 6 7 8 9
template <typename T>
T Array<T>::operator() (Array::uint_t row, Array::uint_t col) const
{
if (row < _rowSize && col < _colSize)
return _ptr[(row*col)+col];
else
// The given row or col are out of bounds!
return ????;
}
Returning a special out-of-bounds value will only mask the runtime error. Basically if you step out of bounds you might not immediately notice, and your program might just start acting weird... making it harder to debug.
On the other hand throwing an exception is very hard to miss. It draws attention to exactly when and where you're stepping out of bounds... making it much easier to find and fix.
@ PiMaster
Oops, I should a reference there. Thanks! So in your example, what would happen if I tried to do something with value aoob? or caoob? For example, if I were using my array class to create a 2D array of images, what would returning 0 (essentially caoob) do?
@ Disch
I've heard that C++'s exception handling is...well, bad. I've avoided working with it too much as a result...but unless I can figure out a better solution, I think that I'll probably do so.