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?
Welcome to the Java Programming Forums
The professional, friendly Java community. 21,500 members and growing!
The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.
>> REGISTER NOW TO START POSTING
Members have full access to the forums. Advertisements are removed for registered users.
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:
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(); } }
Please use [highlight=Java] code [/highlight] tags when posting your code.
Forum Tip: Add to peoples reputation by clicking the button on their useful posts.
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
Please use [highlight=Java] code [/highlight] tags when posting your code.
Forum Tip: Add to peoples reputation by clicking the button on their useful posts.
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)
boolean success = false; while (!success) { try { // code success = true; } catch (Exception e) { // code } }