6

Here is what I want to do: In the loop, if the program finds an error, it will print out "Nothing" and go to the next loop (skips print out ""Service discovered at port: " + px + "\n"

   for(int px=PORT1; px <=PORT2; px++) { //search
       try{

           Socket s = new Socket(IPaddress,px);
       } catch(Exception e) {
               System.out.print("Nothing\n");
               // I want to go to next iteration

           }
       System.out.print("Service discovered at port: " + px + "\n");
   }

What code should I put in the catch? "break" or "next" or ??? (This is java)

Cœur
  • 37,241
  • 25
  • 195
  • 267
John
  • 3,888
  • 11
  • 46
  • 84

4 Answers4

15

Use the continue keyword:

continue;

It'll break the current iteration and continue from the top of the loop.

Here's some further reading:

continue Keyword in Java

Community
  • 1
  • 1
Michael
  • 7,348
  • 10
  • 49
  • 86
14

If you want to only print out a message (or execute some code) if an exception isn't thrown at a particular point, then put that code after the line that might throw the exception:

try {
    Socket s = new Socket(IPaddress,px);
    System.out.print("Service discovered at port: " + px + "\n");
} catch(Exception e) {
    System.out.print("Nothing\n");
}

This causes the print not to execute if an exception is thrown, since the try statement will be aborted.

Alternatively, you can have a continue statement from inside the catch:

try {
    Socket s = new Socket(IPaddress,px);
} catch(Exception e) {
    System.out.print("Nothing\n");
    continue;
}
System.out.print("Service discovered at port: " + px + "\n");

This causes all of the code after the try/catch not to execute if an exception is thrown, since the loop is explicitly told to go to the next iteration.

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
3

The keyword you're looking for is continue. By putting continue after your print statement in the catch block, the remaining lines after the end of the catch block will be skipped the next iteration will begin.

Nate W.
  • 9,141
  • 6
  • 43
  • 65
1

Either

  • Use the continue keyword in the exception block
  • Move the "Service..." to the end of the try block
dfb
  • 13,133
  • 2
  • 31
  • 52