0

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 mainenter image description hereenter image description here

Dilip Bobby
  • 323
  • 5
  • 15

3 Answers3

4

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(...).

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • 1
    Maybe add a break statement after "do something" . – Arnaud Dec 12 '15 at 06:35
  • 1
    Possibly. It depends on precisely what the OP wants to do. – Stephen C Dec 12 '15 at 06:43
  • @StephenC I think he wants to restart the loop so label? – Michael Queue Dec 12 '15 at 06:44
  • 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
  • OP, I think this answers your question. – kasyauqi Dec 12 '15 at 07:18
1

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");
        }
    }
}
CodeBreaker
  • 301
  • 2
  • 9
1

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){}
    }
}
Ramesh-X
  • 4,853
  • 6
  • 46
  • 67