Session 11 |
The keyword Finally
Last session (about streams), it was said that the streams must be closed once the program finishes working with them:
public static String myFirstLine(File myFile) throws IOException { BufferedReader myReader = new BufferedReader(new InputStreamReader(new FileInputStream(myFile), "UTF-8")); String line = myReader.readLine(); myReader.close(); return line; }
This code is not ideal. If the readLine
method causes an exception, the myFirstLine
method will be stopped and the program will never close the stream (close
).
In such programs, we want some code to be executed regardless of whether an exception occurs or is caught. Java has a finally
clause that can be used to accomplish this objective. The finally
block is added after the try
block and its body is always executed - after the try
has finished it work (even if it contains the return
statement) or try
block is stopped.
The correct version of the code above:
public static String myFirstLine(File myFile) throws IOException { BufferedReader myReader = new BufferedReader(new InputStreamReader(new FileInputStream(myFile), "UTF-8")); try { return myReader.readLine(); } finally { myReader.close(); // this block is executed even if the try block causes an exception } }
The same result can be achieved using the try-with-resources
syntax:
public static String myFirstLine(File myFile) throws IOException { try (BufferedReader myReader = new BufferedReader(new InputStreamReader(new FileInputStream(myFile), "UTF-8"))) { return myReader.readLine(); } // the myReader stream is closed even if the try block causes an exception }
Try-with-resources
syntax forces the compiler generate automatically the finally
block after the try
block.
Try-with-resources
, finally
and catch
can also be combined in the program:
try (InputStream is = new FileInputStream("myFile.txt")) { .. return result; } catch (IOException e) { // if the IOException exception is thrown } catch (RuntimeException e) { // if the RuntimeException exception is thrown } finally { // this block is executed anyway }
If an object must be closed (e.g. streams), use try-with-resources
! This is the easiest and the most secure way to close objects. Try-with-resources must become a habit because we will need it all the time. Not closed streams is a typical mistake during the tests. Check Task 1.
Session 11 |