在 Java 中使用 break/continue 退出 try 块
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15983691/
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
Exiting a try block using break/continue in Java
提问by Phoenix
In Java docs I'm reading this: The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break.
在 Java 文档中,我正在阅读:finally 块总是在 try 块退出时执行。这确保即使发生意外异常也能执行 finally 块。但 finally 不仅仅用于异常处理——它允许程序员避免通过 return、continue 或 break 意外绕过清理代码。
When would you ever exit a try block with a break or continue ? The only scenarios I can think of is you are running a loop inside of a try block and you exit using a break/continue but that should just exit outside of a loop and not the try block itself right?
你什么时候会用 break 或 continue 退出 try 块?我能想到的唯一情况是您在 try 块内运行一个循环,然后使用 break/continue 退出,但这应该只是在循环外退出,而不是 try 块本身,对吗?
回答by Stephen C
When would you ever exit a try block with a break or continue?
你什么时候会退出 try 块并中断或继续?
When you have a try
insidea loop; e.g.
当你有一个try
内部循环时;例如
for (Cat cat : cattery) {
try {
cat.removeFromCage();
cat.healthCheck();
if (cat.isPedigree()) {
continue;
}
cat.spey();
} finally {
cat.putBackInCage();
}
}
OK ... so there are more elegant ways of writing that "code" ... but it is just an illustration.
好吧……所以有更优雅的方式来编写“代码”……但这只是一个例子。
The only scenarios I can think of is you are running a loop inside of a try block and you exit using a break/continue but that should just exit outside of a loop and not the try block itself right?
我能想到的唯一情况是您在 try 块内运行一个循环,然后使用 break/continue 退出,但这应该只是在循环外退出,而不是 try 块本身,对吗?
That is right.
没错。
FWIW, any piece of code that involves breaking out of a try block or returning from a catch or finally or any of the other "edge case" things should probably be simplified. The JLS specifies clearly what happens in these scenarios ... but that doesn't mean you should use them in a real program.
FWIW,任何涉及打破 try 块或从 catch 或 finally 或任何其他“边缘情况”返回的代码都应该被简化。JLS 清楚地指定了在这些场景中会发生什么……但这并不意味着您应该在实际程序中使用它们。
回答by Ivan Zelenskyy
Java has labels. And labels usually used with break and continue operator. So, code:
Java 有标签。标签通常与 break 和 continue 运算符一起使用。所以,代码:
outer: for (int i=0; i < 1; i++){
for (int j = 0; j < 1; j++) {
System.out.println("j:"+j);
continue outer;
}
System.out.println("i:"+i);
}
will print only "j:0"
将只打印“j:0”
And because break and continue are 'labeled', you can use "try" statement inside loop block, and inside that block you can try to call "continue" or "break outer_loop". But "finally" statement prevents that exit, as it described in your citation.
因为 break 和 continue 被“标记”,你可以在循环块内使用“try”语句,在该块内你可以尝试调用“continue”或“break outer_loop”。但是“最终”声明阻止了退出,正如您的引文中所描述的那样。
回答by Ryan Stewart
For a completely contrived example:
对于一个完全人为的例子:
import java.io.*;
public class Foo {
public static void main(String[] args) throws IOException {
for (int i = 0; i < 10; i++) {
File file = new File("file-" + i);
FileWriter out = null;
try {
out = new FileWriter(file);
if (file.exists()) return;
out.write("Number " + i);
if (i % 2 == 0) continue;
else if (i % 3 == 0) break;
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
out.close();
}
}
}
}
It's perfectly natural that you might want to return, break, or continue (or throw an exception) inside a try. In this example, if the finally weren't guaranteed to execute, you'd have a resource leak.
您可能想要在 try 中返回、中断或继续(或抛出异常),这是非常自然的。在这个例子中,如果不能保证 finally 执行,就会出现资源泄漏。
And yes, this particular problem is solved by try-with-resource in JDK7.
是的,这个特殊问题是通过JDK7 中的 try-with-resource解决的。
回答by Nerdwood
Yes, break
/continue
should only affect the loop, not the try
/catch
/finally
block. The doc is just pointing out that it is easy to accidentally miss (not execute) a block of cleanup code when trying to handle exceptions, especially with those sneaky break
s and continue
s that change the flow!
是的,break
/continue
只会影响循环,而不是try
/ catch
/finally
块。该文档只是指出在尝试处理异常时很容易意外错过(而不是执行)一段清理代码,尤其是那些改变流程的偷偷摸摸的break
s 和continue
s !
The finally block should always be executed, unless System.exit()
is called or the JVM crashes!
该finally块应该总是被执行,除非System.exit()
被称为或JVM崩溃!
回答by vel
Yes possible, Using break statementwe can exit try blockwith help of labeland without using loop.
是的,使用break 语句,我们可以在label 的帮助下退出 try 块,而无需使用 loop。
tryLabel:
try {
if(true)
break tryLabel;
System.out.println("try");
}catch(Exception e) {
System.out.println("catch");
e.printStackTrace();
}finally{
System.out.println("finally");
}