java 如何进入下一次迭代
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4939945/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to go to next iteration
提问by John
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"
这是我想要做的:在循环中,如果程序发现错误,它将打印出“Nothing”并进入下一个循环(跳过打印出“在端口发现的服务:” + 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)
我应该在 catch 中放入什么代码?“休息”或“下一个”或???(这是java)
回答by Michael
Use the continue keyword:
使用 continue 关键字:
continue;
It'll break the current iteration and continue from the top of the loop.
它会中断当前的迭代并从循环的顶部继续。
Here's some further reading:
这是一些进一步的阅读:
回答by templatetypedef
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.
print
如果抛出异常,这将导致不执行,因为try
语句将被中止。
Alternatively, you can have a continue
statement from inside the catch
:
或者,您可以continue
从内部获得声明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.
如果抛出异常,这会导致 try/catch 之后的所有代码都不会执行,因为循环被明确告知要进行下一次迭代。
回答by Nate W.
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.
您要查找的关键字是continue
。通过将continue
打印语句放在catch
块中,块结束后的剩余catch
行将在下一次迭代开始时被跳过。
回答by dfb
Either
任何一个
- Use the
continue
keyword in the exception block - Move the "Service..." to the end of the try block
continue
在异常块中使用关键字- 将“Service...”移动到 try 块的末尾