Writing functions which handle invalid inputs in C++

66 views Asked by At

In C++, how to handle function outputs , if the inputs are invalid. Say, I am writing a function to multiply two matrices. How to deal with it if the two matrices cannot be multiplied (due to in-compatible shape)?

I tried to use std::optional , but then it has created other problems. Since the output is expected to be std::optional(Matrix) ,I have to write all the other functions in the class (like print Matrix()) with the expected output as std::optional , which seems unnecessary.

2

There are 2 answers

0
RoyA On BEST ANSWER

I think this could be fun. Just add a 'valid' property to the Matrix and check it only when you want to!

class Matrix
{
public:
    Matrix Multiply(Matrix other)
    {
       return Multiply(other, m_isValid);
    }

    bool IsValid()
    {
        return m_isValid;
    }

private:
    bool m_isValid;
    Matrix Multiply(Matrix other, bool& isValid);
};
1
Rai Muhammad Tabish On

Before attempting to multiply two matrices, ensure that the number of columns in the first matrix matches the number of rows in the second. If this condition is not met, throw an exception.