3
We know the need to close resources (files, connections, also called Resources) consumed in Java, such as OutputStream
and InputStream
. When we don’t close them, we create performance problems and prevent the Garbage Collector from releasing memory and finishing the Object, among other problems such as memory Leaks.
Idiom Try-catch-Finally
Below we have the main language that contemplates the above mentioned scenario:
This code opens a file, reads its lines, printa each one, captures exception if it occurs, and finally in case of success or error, closes the resource, ie the file.
public static void main(String[] args) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\testing.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch(IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
In the above code the compiler does not require us to add the block finally
, which is important to close the BufferedReader
and all other IO objects associated with it, whether or not exceptions and errors have occurred. Without the finally
our code can perfectly compile, run in test environments, and only reveal production failure.
How not to include the finally
and still close Connection
s, Statement
s, ResultSet
s, Reader
s, Writer
s and even our objects that require a closure method - close()
?