Easy java core-java

How do try-catch-finally and try-with-resources work?

The 30 second answer

try holds the code that might fail, catch handles a specific exception type, and finally always runs for cleanup. try-with-resources is the better way to clean up: anything that implements AutoCloseable, like a stream or a JDBC connection, is declared in the try parentheses and closed automatically in reverse order, even when an exception is thrown. If close also throws, that exception is kept as a suppressed exception instead of hiding the original one.

<!-- level: 1 --> <!-- must_know: true -->

try (Connection conn = dataSource.getConnection();
     PreparedStatement ps = conn.prepareStatement("select ...")) {
    // use ps
} catch (SQLException e) {
    throw new DataAccessFailure("query failed", e);
}

A test with two resources that throws inside the body printed, on Java 21:

open A
open B
body
close B
close A
caught boom
finally

So resources close in reverse order of opening, before catch and finally run.

  • Any class that implements AutoCloseable (or Closeable) can be used.
  • If both the body and close() throw, the body's exception is thrown and the close() exception is added to it as a suppressed exception (getSuppressed()). With a manual finally, an exception from closing can hide the real error.
  • Catch the most specific exceptions first; multi-catch catch (IOException | SQLException e) handles several types in one block.
Sources (3)
  1. Java tutorial: The try-with-resources statementdocs.oracle.com
  2. Javadoc: java.lang.AutoCloseabledocs.oracle.com
  3. dev.java: Catching and handling exceptionsdev.java