I'm not a fan of exceptions, so I try to find alternatives. Which alternative is possible depends on the context.
How is the matrix returned? If by pointer, then you can simply return a nullptr. If by value or reference, that's not an option. Checking for nullptrs is easy and should be done anyway in most cases.
Personally, I prefer using 'assert': it checks whether a condition is true, and if not throws an error and quits. It's nice because they are automatically ignored in release builds and they are very easy to include. However, it's not useful if something else than program logic can cause these 'errors' (e.g. user input), because you can't simply verify everything at compile time.
Lastly, making sure the conditions are good
before calling a function is often easier than
during, because the function itself might be stuck with a certain return type or flow restriction.
As an example, think of a Matrix Squaring function. Squaring requires a matrix to be NxN, which is easy to check:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
// By nullptr
Matrix* sqMat(Matrix& mat) {
Matrix *squared;
if (mat.rows != mat.cols) squared = nullptr;
else squared = new Matrix(mat * mat);
return squared;
}
// Using assert to verify
#include <cassert>
Matrix sqMat(Matrix& mat) {
assert(mat.rows == mat.cols); // Quits and errors if unequal.
return mat*mat;
}
// Pre-verification
if (matrix.cols == matrix.rows) squared = sqMat(matrix);
|