1

A coworker just unsettled me concerning finally blocks. He claimed that if multiple resources are closed inside a finally block, I do not have to worry about exception handling.

So if I close my resources like this

try {
  // do stuff
} catch(Exception e) {
  // handle stuff
} finally {
  resource1.close();
  resource2.close();
}

and an exception occurs at resource1.close(), will the close() method of resource2 get called?

saxum
  • 107
  • 2
  • 10
  • 7
    This is 2016; why don't you use try-with-resources? Also, try and test it yourself – fge Feb 24 '16 at 15:49
  • Following @fge's suggestion, before trying and testing, take a look at both the Java [documentation](http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.20.3.2) and [tutorial](http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html). – António Ribeiro Feb 24 '16 at 15:55
  • 1
    apparently your co-worker doesn't know what he's talking about. also for whether to use try-with-resources, see http://stackoverflow.com/q/26516020/217324 – Nathan Hughes Feb 24 '16 at 16:06

2 Answers2

1

A simple check would confirm:

class MyResource implements AutoCloseable {
  private final String name;
  MyResource(String name) { this.name = name; }

  @Override public void close() throws IOException {
    System.out.println("Closing " + name);
    throw new IOException();
  }
}

public static void main(String[] args) throws IOException {
  MyResource a = new MyResource("a");
  MyResource b = new MyResource("b");
  try {
  } finally {
    a.close();
    b.close();
  }
}

This would print "Closing a" and then print a stack trace; "Closing b" would not be printed. In contrast:

  try (MyResource a = new MyResource("a");
       MyResource b = new MyResource("b")) {
  }

would print both.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
0

That depends. If the only exception throwing things (explicitly or potentially) you have inside your try-catch block are close operations, you wouldn't need exception handling. However, most of the times, the close operations are themselves declared as throwing exceptions, thus, you'd need to put them inside a try-catch block anyway.

Felipe Martins Melo
  • 1,323
  • 11
  • 15