Introduction to Java try with resources

One of the biggest problem that creeeps into production code is resource leaks. Often resources like database connections, open files are not closed mostly in exception cases or sometimes even in the normal or happy path scenarios. Typically side effects of such leaks shows up when the system is under load or is soaked for a long time. These are difficult to troubleshoot as they manifest in production in completely unrelated ways...


Would not it be great if these resources were autoclosed irrespective of whether the code executed a success path or error path without being dependendent on the programmer to take care of it by explicitly handling resource closing code in both success and failure cases.

Java 7 introduced a feature called 'try with resources''. Strangely it is not very popular even after being around for more then a decade.
Let's take a quick look at this feature and see how you can benefit from it.

Sample code wihout using try with resources Scanner sc = null; try { sc = new Scanner(new File("sample.txt")); while (sc.hasNext()) { System.out.println(sc.nextLine()); } } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if (sc != null) { sc.close(); } }
Sample code using try with resources try (Scanner sc = new Scanner(new File("sample.txt"))) { while (sc.hasNext()) { System.out.println(sc.nextLine()); } } catch (FileNotFoundException e) { e.printStackTrace(); }

Benefits of using are obvious -

  • The code is shorter.
  • No leaky code - Resources are closed when they go out of scope.

  • So if you have are working on a project that uses Java 7 or higher & whenever you open a resource ( file, database connection etc) check if the resource you are using implements AutoCloseable then it is time use Try with resources then just vanilla Try Catch finally statement

    Here are some additional resources about try with resources

  • Most viewed/liked YouTube video on Try with resources
  • Official documentation on Try with resources

  • Similar blogs that you may find interesting
  • Java records Introduction
  • Java Refactoring

    Clicky