Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, what is the best way of continuing to call a function until no exception is thrown?

In my Java code, I have a function called getAngle() which sometimes throws a NoAngleException. Is the following code the best way of writing a function that keeps calling getAngle() until no exception is thrown?

public int getAngleBlocking()
{
    while(true)
    {
        int angle;
        try
        {
            angle = getAngle();
            return angle;
        }
        catch(NoAngleException e)
        {

        }
    }
}

Or would it be a better idea to rewrite getAngle() to return NaN upon error?

like image 209
Eric Avatar asked Oct 29 '09 11:10

Eric


2 Answers

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
like image 92
Droo Avatar answered Sep 28 '22 09:09

Droo


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.

like image 38
ziggystar Avatar answered Sep 28 '22 09:09

ziggystar