Ad Infinitum
Ad Infinitum

Reputation: 3696

Sophisticated exception handling in Java

In the following scenario,

public void fooMethod()
{
 try
 {
  methodToCall();

 }catch( FooException exception )
 {
  methodToCall();
 }
}


private int methodToCall() throws FooException
{
  throw new FooException();
}

I want to callmethodToCall (for example) 10 times to try if it succeeds.

Because of the fact that in the catch block, no exception is caught and with the above given example, the methodToCall is called two times in total (one in the try block and one in the catch block.)

How should I design the code so that methodToCall will be called 10 times even if it throws the given exception.

Edit

The actual fooMethod is much more complicated than this and I cannot call it recursively because several other jobs are done than before this try-catch clause.

Upvotes: 1

Views: 72

Answers (2)

utkarsh31
utkarsh31

Reputation: 1539

public void fooMethod()
{
int counter = 0 ;
 while(counter < 10){
  try
   {
    methodToCall();
    counter = 11;
   }catch( FooException exception )
   {
     counter++;
   }

}
}

Upvotes: 1

Anthony Raymond
Anthony Raymond

Reputation: 7862

The for loop will ensure 10 calls are made. And the try catch will prevent exiting from the loop.

public void run10TimesWhatsoever() {
    for(int i = 0; i < 10; ++i) {
        try {
          methodToCall();
        } catch (final FooException ignore) {
        }
    }
}

However, if you want to call at MOST 10 times and stop when it succeed you may use something like that

public void attemptUpTo10Times() {
    for(int i = 0; i < 10; ++i) {
        try {
            methodToCall();
            break; // exit the loop if no exception were thrown
        } catch (final FooException ignore) {
            if (i == 9) {
                throw new IllegalStateException("Failed 10 times in a row");
            }
        }
    }
}

Upvotes: 1

Related Questions