I’m running a code that throws an exception,I want run the exception code continuously whenever the exception is thrown it has go to starting and should start the program from starting.
Here is my exception method and main

- 323
- 5
- 15
-
2pls dont post a screenshot of the code but text instead – Dennis Kriechel Dec 12 '15 at 06:28
-
okay ! @DennisKriechel – Dilip Bobby Dec 12 '15 at 08:43
3 Answers
You need to put the try / catch in a loop; e.g. something like this:
public static void main(String[] args) {
while (true) {
try {
// do something
} catch (Exception ex) {
// report ex
}
}
}
Now, the above will repeat the // do something
code block until the program is killed, which may not be what you want. If you wanted to terminate when the // do something
succeeds, then one solution would be to add a break
statement at the end of it. Others could be to set a flag and loop until the flag is set, or even call System.exit(...)
.

- 698,415
- 94
- 811
- 1,216
-
1
-
1
-
-
I just wanted to run without stopping, even if program throws the exception the exception is caught in the catch block and method should run again and that running method will throw the exception again & again i should not stop throwing the exception. – Dilip Bobby Dec 12 '15 at 06:50
-
1@MichaelQueue - I think it is unclear what he wants to do if the code in the block succeeds. My answer is intended to get him thinking in the right direction ... not provide a potted solution. I'm assuming he understands enough Java to understand the various ways to terminate a loop ... if that is what he wants to do. – Stephen C Dec 12 '15 at 06:50
-
I think I get what you're wanting.
You can explicit throw a generic exception in your try statement which prevents having to generate one through "bad code". You can also pass the "message" you wan to display to this exception and print it out in the catch statement along with the done. Since the exception is handled in the exc() method you won't need the try/catch statement in the main method. It could just be one line.
exc();
public static void exc() {
for(;;){
try{
throw new Exception("Exception");
} catch (Exception e) {
System.out.println(e.getMessage());
System.out.println("Done");
}
}
}

- 301
- 2
- 9
Try this one..
public static void main(String[] args) {
Test_exception_main u = new Test_exception_main();
while(true){
try{
u.exc();
}catch(Exception e){}
}
}

- 4,853
- 6
- 46
- 67