How to proceed to the next intervention

Here is what I want to do: in the loop, if the program detects an error, it will output “Nothing” and go to the next loop (skips the printout of “Service found on 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 interation } System.out.print("Service discovered at port: " + px + "\n"); } 

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

+6
java for-loop try-catch
source share
4 answers

If you want to print a message (or execute some code), if the exception is not thrown at a specific point, then put this code after the line that may cause 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 print fail if an exception is thrown, since the try will be aborted.

Alternatively, you can have a continue statement inside 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 calls all the code after try / catch fails if an exception is thrown, since the loop explicitly tells you to go to the next iteration.

+13
source share

Use the continue keyword:

 continue; 

It will break the current iteration and continue working from the top of the loop.

Here is another reading:

continue keyword in java

+15
source share

The keyword you are looking for is continue . By placing continue after the print statement in the catch , the remaining lines after the end of the catch will be skipped, the next iteration will begin.

+3
source share

Or

  • Use the continue keyword in the exception block
  • Move "Service ..." to the end of the try block
+1
source share

All Articles