1

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.

2
  • 5
    you can put your try catch inside a loop Commented Nov 28, 2017 at 10:47
  • use a counter in try block, and catch block make it zero if exception occurs. and put code inside loop Commented Nov 28, 2017 at 10:48

2 Answers 2

0

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"); } } } } 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. The second solution of your answer does the job for me:)
0
public void fooMethod() { int counter = 0 ; while(counter < 10){ try { methodToCall(); counter = 11; }catch( FooException exception ) { counter++; } } } 

2 Comments

Thank you for your answer. This is also another good solution.
always happy to help :)