I've read that resources initialized in a try-with-resources block are only in scope for the duration of the block.
If that's the case, then how does this code seem to get around that?
public class Main {
public static void main(String[] args) throws Exception {
final Main main = new Main();
try {
final char[] buffer = new char[10];
StringReader stringReader = main.testStream();
System.out.println(stringReader.read(buffer, 0, 10));
} catch (IOException e) {
System.out.println("expected IOException caught here");
}
try {
HttpResponse response = main.tryResponse();
response.getEntity();
System.out.println("should not reach this line if response is out of scope");
} catch (Exception e) {
System.out.println("why no IOException here?");
}
}
StringReader tryStream() throws IOException {
try (StringReader reader = new StringReader("string")) {
return reader;
}
}
HttpResponse tryResponse() throws IOException {
CloseableHttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet("http://www.google.com");
try (CloseableHttpResponse response = client.execute(request)) {
return response;
}
}
}
What are java best practices concerning situations like this?