adadaae12313412 adadaae12313412 - 4 months ago 21
C++ Question

What to return from a method if certain conditions haven't been met?

I'm writing a Matrice class (for practice sake) and when I wrote the method to multiply two Matrice objects I had to check if certain conditions are met for matrix multiplication:

Matrix Matrix::mul(const Matrix &mat)
if(col != mat.row)
//we cannot multiply in this case
//create temp object result
//perform multiplication
return result;

Now I'm curious on what to do if the condition hasn't been met because back in main.cpp I'd write something like this:

Matrix a = b.mul(c);

Now what if b and c cannot be multiplied, what should I return?
Is the best way to throw an exception, to just force the person using that class to send compatible matrices, is there another better way?


Don't return anything, throw an exception instead:

if (failure)
    throw std::runtime_error("Exception!!");

You can throw any of the different exceptions that suits your case more.

By the way, you could take a look at my project called Matrix on GitHub for an example of how one could create such a class to operate on matrices.