Is it possible to execute the code in the try block again after an exception in caught in catch block?

后端 未结 7 830
灰色年华
灰色年华 2021-02-05 06:18

I want to execute the code in the try block again after an exception is caught. Is that possible somehow?

For Eg:

try
{
    //execute some code
}
catch(E         


        
7条回答
  •  后悔当初
    2021-02-05 06:45

    Put it in a loop. Possibly a while loop around a boolean flag to control when you finally want to exit.

    bool tryAgain = true;
    while(tryAgain){
      try{
        // execute some code;
        // Maybe set tryAgain = false;
      }catch(Exception e){
        // Or maybe set tryAgain = false; here, depending upon the exception, or saved details from within the try.
      }
    }
    

    Just be careful to avoid an infinite loop.

    A better approach may be to put your "some code" within its own method, then you could call the method from both within the try and the catch as appropriate.

提交回复
热议问题