"Proper way" to terminate program to avoid error

I'm writing a basic class/program to manipulate matrices - say add/subtract/multiply.

When adding matrices, the dimensions must be identical for the operation to be defined. However, say I call the addition operation on two matrices whose dimensions don't match.

At the moment, my + function checks the dimensions, sees that they don't match and then uses return(1) to exit the program. Clearly this isn't ideal! I want the program to print an error message, but then how would I get my function to return something without throwing an error?

(currently the + functions returns a matrix object, where matrix is a class I have defined. Therefore, returning 0 and doing something like cerr << "Error. Dimensions do not match" << endl; doesn't work)
Last edited on
Throw an exception. This is exactly what they're for.

EDIT:

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Matrix operator + (const Matrix& lhs, const Matrix& rhs)
{
    if( cant_add_matrixes )
        throw std::invalid_argument( "Some text to explain what went wrong." );
}


//....

void doingSomeBigOperationWithMatrixes()
{
    try
    {
        // ... bunch of code
        matrix_c = matrix_a + matrix_b;
        // ... more code
    }
    catch(std::exception& e)
    {
        std::cout << e.what() << endl;  // log the error
    }
}
Last edited on
Not seen that before. I'll read up about it.

Just a QQ though, it means you don't have to return something?
No, you don't have to return anything. The throw will exit the function in this case.

It'll make sense when you read up on exceptions.


The general flow is that when inside a try block, it will execute code as normal until it hits a throw -- at which case code inside the try block will completely stop, and the program will basically jump to the following catch block.




Exceptions and exception handling is tricky for beginners. They tend to either use them too much, or use them incorrectly. It's just one of those things that takes time to really figure out.
Yeah I've found that now. My program outputs the error message from the catch block but it still crashes afterwards. I'll have a play with my code ..
Something else must be causing it to crash. Won't be able to diagnose without seeing more code.
Sorted it. Like you said, beginners place catch blocks incorrectly a lot!

Thanks for your help :)
Last edited on
Topic archived. No new replies allowed.