尝试使用资源时不工作,但尝试工作没有资源!
这是这种情况的一个简单例子。我在工作项目中遇到了这个“bug”。 当我使用尝试没有资源在资源尝试中不工作,但尝试不使用资源
try {
Resources resources = getResources()
// some code here, look below
}
我只有一个我的周期的迭代,这是正确的,因为我具备的条件,“如果真再突破”,但是当我改变了尝试无追索权的尝试资源。
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
显示其他版本,有些东西告诉我你不要在那里打电话。 –
@pablochan为什么?休息不起作用?如果编译器删除了我的条件,它不会删除“break”。例如,如果(true){“do something”}将被优化,它将变成“做某事”。 – GermanSevostyanov