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)
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.