Arvutiteaduse instituut
  1. Kursused
  2. 2018/19 kevad
  3. Objektorienteeritud programmeerimine (Narva Kolledž) (LTAT.NR.003)
EN
Logi sisse

Objektorienteeritud programmeerimine (Narva Kolledž) 2018/19 kevad

  • Home
  • Materials
  • Java Glossary
  • Source Example
  • Cheat sheet (S1-S6)
  • Grading
  • Links
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
  • Arvutiteaduse instituut
  • Loodus- ja täppisteaduste valdkond
  • Tartu Ülikool
Tehniliste probleemide või küsimuste korral kirjuta:

Kursuse sisu ja korralduslike küsimustega pöörduge kursuse korraldajate poole.
Õppematerjalide varalised autoriõigused kuuluvad Tartu Ülikoolile. Õppematerjalide kasutamine on lubatud autoriõiguse seaduses ettenähtud teose vaba kasutamise eesmärkidel ja tingimustel. Õppematerjalide kasutamisel on kasutaja kohustatud viitama õppematerjalide autorile.
Õppematerjalide kasutamine muudel eesmärkidel on lubatud ainult Tartu Ülikooli eelneval kirjalikul nõusolekul.
Courses’i keskkonna kasutustingimused