Search code examples
javamethodsexecute

How to recall a method specified no. of times when exception occurs


I tried to re-execute a method specified number of times when exception occurs in a method, but I am unable re-execute the method

    int maxretries=10;
    void show(){
         try{
        display();
       }
    catch(Exception e)
    {
     for(int i=1;i<maxretries;i++){
        display();//on first retry only I am getting exception
    }
    }
    }

when I run the code it is executed for first retry and I am getting exception but I want to reexecute display() method upto it is excuted successfully with in maximum retries.


Solution

  • The call you coded inside the catch is not inside a try, so it will not catch exceptions.

    You need to use other concepts to do this, either calling the whole function again, or coding a successive try block inside the catch (and a further try block inside that catch block, etc.), or coding the loop around the whole try block (probably the best approach).