【发布时间】:2016-09-29 17:58:01
【问题描述】:
Break 在尝试使用资源时不起作用,但在尝试没有资源时起作用!
这是这种情况的一个简单示例。我在工作项目中发现了这个“错误”。
当我在没有资源的情况下使用 try 时
try {
Resources resources = getResources()
// some code here, look below
}
我的周期只有一次迭代,这是正确的,因为我有条件“如果为真,则中断”,但是当我更改 try 而没有追索 try WITH 资源时。
try (Resources resources = getResources()) {
// some code here, look below
}
我惊呆了!循环变得无穷无尽!为什么?
完整代码:
public class Test {
public static void testTryWithResAndBreak() {
while (true) {
System.out.println("we are in (while(true))");
try (Resources resources = getResources()) {
System.out.println("We are in try block");
if (true) {
System.out.println("We are in the if(true) now! Next step is break");
break;
}
System.out.println("OOOOO___OOOO WE ARE HERE!!!");
resources.writeSomething();
} catch (Exception e) {
System.out.println("Catched exception");
}
}
}
private static class Resources implements AutoCloseable {
@Override
public void close() throws Exception {
System.out.println("Resources closed");
throw new Exception("Exception after closed resources!");
}
public void writeSomething() {
System.out.println("i wrote something");
}
}
private static Resources getResources() {
return new Resources();
}
public static void main(String[] args) {
testTryWithResAndBreak();
}
}
【问题讨论】:
-
if (true) {...}可能会被编译器删除。你那里有实际情况吗? -
显示另一个版本,有些东西告诉我你不要在那里打电话。
-
@pablochan 为什么?休息没用?如果编译器删除了我的条件,它并没有删除“break”。例如如果 (true) { "do something" } 将被优化,它将变成只是 "do something"。
-
@JornVernee 我认为这不会改变问题。当我尝试使用资源时,“中断”不起作用。当我使用尝试!没有!资源“中断”正常工作。只需复制我的代码并运行,您就会看到它。
-
我已经可以看到它了,我也知道它为什么不起作用了。我需要查看其他版本才能告诉您区别。
标签: java try-catch try-with-resources