October 22, 2024
Chicago 12, Melborne City, USA
java

Why can't I pass lambda inline into try-with-resources


Help me understand why the following code doesn’t compile. AutoCloseable is a single abstract method interface and I am able to assign it to lambda expression, just not in try-with-resources context:

class Main {
  public static void main(String[] args) {
    try (AutoCloseable test = () -> System.out.println("Closing")) {}
  }
}

I’m getting following compilation error and trying to wrap my head around – why?

error: unreported exception Exception; must be caught or declared to
be thrown

exception thrown from implicit call to close() on resource
variable ‘test’



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video