IF i am using try/catch block and an exception is caught, how can i go back to the initial try block to, 'try' again?
Printable View
IF i am using try/catch block and an exception is caught, how can i go back to the initial try block to, 'try' again?
Hello rsala004.
Say you have a method called myMethod with a try/catch block in it. The exception is caught in the catch part so in catch you just need to call the method again.
Example:
Code :public class rsala004 { /** * JavaProgrammingForums.com */ public void myMethod(){ try{ // whatever code here }catch(Exception e){ // When exception thrown, myMethod run again [B]myMethod();[/B] } } public static void main(String[] args) { rsala004 r = new rsala004(); r.myMethod(); } }
ah, clever thanks
Be somewhat careful with exceptions though, the specific exception might have been cast to tell you something is wrong which can't really be fixed which will make your method call itself and produce a stack overflow.
// Json
You can avoid the potential stack overflow problem with a non-recursive solution (though, again, if you don't follow the above suggestions, it'll create an infinite loop)
Code :boolean success = false; while (!success) { try { // code success = true; } catch (Exception e) { // code } }