Using for loop variable when inner exception occurs

Hello,
Is it correct to use a value of variable 'x' from the for loop inside catch if exception occurs inside the loop?
Or how would you suggest to rewrite this code?
I cannot change the logic of getValue() function since it comes from external library (it is a normal operation when it throws an exception, so the only way is to catch it and process accordingly).

1
2
3
4
5
6
7
8
9
10
double start = 0;
double step = 0.001;

try{
     for(double x = start + step; x <= rightPoint; x += step ){
	value = getValue(x); //exception can happen here
     }
}catch (...){
     start = x; //is it correct to use x here???
}


Thank you!
No you can't do that because x is only in scope inside the loop. If you want to be able to use x in the catch you'll have to define x outside the try/catch block.
Hi,
This is unrelated to your actual question, but I mention it to help you out in future :+)

It's rather bad news to use a double in a for loop like that anyway - stick to integers.

double and float are not represented exactly, so that can cause you problems, even though you use a relational operator. If rightPoint is 0.01 , there is no real way of knowing whether x might be 0.00999999999997 or 0.01000000000002 say, so you could get off by one errors. There is a chance that it might work for a particular set of numbers. But it won't work for any set of numbers - changing any 1 of the 3 numbers might cause it to fail.

A better way to do things, is to calculate how many times you need to loop as an int (and use that in the loop condition), using start stop and step values: NumTimesLoop = (stop - start) / step. Then make use of a rounding function, and cast it to int. Then you can use ints in the normal way (from 0 to Num) with the for loop, and change the value of x in the body of the loop.

In c++11 there are functions to return the next greater double value

http://en.cppreference.com/w/cpp/numeric/math/round
http://en.cppreference.com/w/cpp/numeric/math/nextafter


Good Luck !! :+)
Yeah, that was a stupid question, I was too tired:)
Rewrote it with while loop. thanks everybody replied!
Topic archived. No new replies allowed.