Skip to content
This repository has been archived by the owner on May 22, 2024. It is now read-only.

Latest commit

 

History

History
14 lines (12 loc) · 640 Bytes

item-09.md

File metadata and controls

14 lines (12 loc) · 640 Bytes

Item 09: Prefer try-with-resources to try-finally

static String firstLineOfFile(String path) throws IOException {
  try (BufferedReader br = new BufferedReader(new FileReader(path))) {
    return br.readLine()
  }
}
  • If exceptions are thrown by both readLine and the invisible close method, the latter exception is suppressed in favor of the former.
  • Multiple exceptions may be suppressed in order to preserve the exception that user actually wants to see.
  • Suppressed exceptions are printed in the stack trace with a suppression notation.
  • Suppressed exceptions can be accessed with the getSuppressed method.