We know of the need to close resources (files, connections, also called resources ) consumed in Java, such as OutputStream
and InputStream
. When we do not close them, we create performance issues and prevent the Garbage Collector from freeing up memory and finishing the Object, among other problems like memory leaks.
try-catch-finally language
Below we have the main language that contemplates the scenario mentioned above:
This code opens a file, reads its lines, printa each, 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 force us to add the block finally
, which is important to close the BufferedReader
and all other IO objects associated with it, with or without exceptions and errors. Without finally
our code can perfectly compile, run in test environments, and only reveal the failure to produce.
Since you do not need to include finally
and still close Connection
s, Statement
s, ResultSet
s, Reader
s, Writer
if even our objects that require a method of closing - close()
?