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(Exception e) { }
If the exception is caught I want to go in the try block again to "execute some code" and try again to execute it.
There is no way of going back from catch to try block. You will have to redesign your code - either wrap each findElement() method in separate try/catch blocks or use a loop as advised in other answers.
Because if an exception is thrown, Code in the finally clause will execute as the exception propagates outward, even if the exception aborts the rest of the method execution; Code after the try/catch block will not get executed unless the exception is caught by a catch block and not rethrown.
When nested try blocks are used, the inner try block is executed first. Any exception thrown in the inner try block is caught in the corresponding catch block. If a matching catch block is not found, then catch block of the outer try block are inspected until all nested try statements are exhausted.
When an exception occurs inside a try block, control goes directly to the catch block, so no other code will be executed inside the try block and the value of res will not change.
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.
If you wrap your block in a method, you can recursively call it
void MyMethod(type arg1, type arg2, int retryNumber = 0) { try { ... } catch(Exception e) { if (retryNumber < maxRetryNumber) MyMethod(arg1, arg2, retryNumber+1) else throw; } }
or you could do it in a loop.
int retries = 0; while(true) { try { ... break; // exit the loop if code completes } catch(Exception e) { if (retries < maxRetries) retries++; else throw; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With