Hey everyone, I've got some code where I'm calculating a geometric mean:
Now sometimes the value of product gets too big for an integer, and I want to somehow catch this error when it happens. I could change it to a long, but I'd still want to catch the overflow error if it happened with a long, so the type of product doesn't really matter to my question. (I can potentially get all sorts of crazy numbers in this code and I need to be able to deal with them all!)Code:include <exception> using std:: overflow_error // space to prevent a smiley! ... try { // Calculate the geometric mean of the values in array prevBids int product = 1; for (int i = 0; i < maxPrevBids; i++) { product *= prevBids[i]; } bid = (static_cast<int>( pow (product, ( 1.00 / static_cast<double>(maxPrevBids))))); } catch (overflow_error &e) { // Some error-handling code }
I tried enclosing the code in a try/catch block like shown above, but when I stepped through the code with the debugger, it didn't throw an exception. It just kept trying to multiply product (resulting in some very weird values for product). If product was an invalid entry for the pow function, then an exception was thrown at the pow function.
Any ideas on how I can catch or prevent this overflow error?