The safest way to use the close()
is indirectly, with the Try-with-Resources. The Try-with-Resources was introduced in Java 7 which was released in 2011. So if you’re seeing older articles, they won’t talk about this feature and will show the old-fashioned management.
An example of the use of Try-with-Resources that’s the one:
try (Connection con = getConnection()) {
// Faz algo com a conexão.
}
The compiler will put on its own a blcoo finally
implicit to close the object con
and already treat all special cases of exceptions in the block try
and exceptions being launched by the method close()
. If you put blocks catch
or a block finally
explicit, the compiler will know how to combine everything harmoniously. See more details in the question "How Try-with-Resources works?".
Call the close()
inside a block that already uses the Try-with-Resources, although possible, it does not usually make much sense, but it would also hardly cause any harmful effect, except if you try to use the closed resource as if it were still open, obviously.
If you can’t use the Try-with-Resources for some reason, prefer to do what the compiler would do if you used: Call the close()
inside the block finally
. For example:
Connection con = null;
try {
con = getConnection();
// ... faz um monte de coisas.
} catch (SQLException e) {
// Faz algo para tratar a exceção, relançar ou encapsular e lançar outra exceção.
} finally {
try {
if (con != null) con.close();
} catch (SQLException e) {
// Faz algo para tratar a exceção, relançar ou encapsular e lançar outra exceção.
}
}
If you are dealing with a case where the resource should remain open after the execution of the method, then in general there are two alternatives:
Return the object that represents the resource that was left open so that the method that called you worry about closing.
Store the object in some class instance attribute and make this class implement AutoCloseable
. The method close()
of that class then delegates to the close()
open resource. This resource should preferably be opened in the constructor.
Example of case 1:
// Deixa o recurso aberto e o retorna.
public InputStream abrirArquivo() {
return new FileInputStream(new File("teste.txt"));
}
// Usa o recurso aberto pelo outro método.
public class utilizaArquivo() {
try (InputStream x = abrirArquivo()) {
// ...
}
}
Example of case 2:
public class ChamadaTelefonica implements AutoCloseable {
private final String destino;
private final InputStream entrada;
private final OutputStream saida;
public ChamadaTelefonica(String destino) {
this.destino = destino;
this.entrada = ...;
this.saida = ...;
}
// Um monte de métodos legais aqui que operar os atributos entrada e saída.
@Override
public void close() throws IOException {
try {
entrada.close();
} finally {
saida.close();
}
}
}
How Try-with-Resources works?
– user28595
Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site.
– Maniero