saxum
saxum

Reputation: 107

If multiple resources are closed inside a finally block, is exception handling necessary?

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?

Upvotes: 1

Views: 906

Answers (2)

Andy Turner
Andy Turner

Reputation: 140319

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.

Upvotes: 1

Felipe Martins Melo
Felipe Martins Melo

Reputation: 1333

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.

Upvotes: 0

Related Questions