Finally
- If an exception is thrown, the finally block is run after the catch block. If no exception is thrown, the finally block is run after the try block completes.
- finally block always at the end
- finally is typically used to close resources such as files or databases
- Example of reading a line from a file
```java
public void oldApproach(Path path1, Path path2) throws IOException {
BufferedReader in = null;
BufferedWriter out = null;
try {
in = Files.newBufferedReader(path1);
out = Files.newBufferedWriter(path2);
out.write(in.readLine());
} finally {
if (in != null) in.close();
if (out != null) out.close();
}
}Autoclosable interface & try-with-resources
Last updated