In Java, what is the best way of continuing to call a function until no exception is thrown?
I'm surprised to read some of the answers to this thread because this scenario is precisely the reason checked exceptions exist. You could do something like:
private final static int MAX_RETRY_COUNT = 5;
//...
int retryCount = 0;
int angle = -1;
while(true)
{
try
{
angle = getAngle();
break;
}
catch(NoAngleException e)
{
if(retryCount > MAX_RETRY_COUNT)
{
throw new RuntimeException("Could not execute getAngle().", e);
}
// log error, warning, etc.
retryCount++;
continue;
}
}
// now you have a valid angle
This is assuming that something outside of the process changed in the meantime. Typically, something like this would be done for reconnecting:
private final static int MAX_RETRY_COUNT = 5;
//...
int retryCount = 0;
Object connection = null;
while(true)
{
try
{
connection = getConnection();
break;
}
catch(ConnectionException e)
{
if(retryCount > MAX_RETRY_COUNT)
{
throw new RuntimeException("Could not execute getConnection().", e);
}
try
{
TimeUnit.SECONDS.sleep(15);
}
catch (InterruptedException ie)
{
Thread.currentThread().interrupt();
// handle appropriately
}
// log error, warning, etc.
retryCount++;
continue;
}
}
// now you have a valid connection
I think you should investigate why getAngle() is throwing an exception and then resolve the problem. If this is random, like input from a sensor, maybe you should wait some time until calling again. You could also make getAngle() blocking, that means getAngle() will wait until a good result is acquired.
Ignoring how you're solving your problem you should have some kind of timeout mechanism, so you don't end up in an endlessloop. This supposes that you don't want to have an possibly infinite loop, of course.
You want to call a method as long as it throws an exception?
This is not programming. You should use the debugger and take a look at the real issue.
And you should never catch an exception without any message or logging!