OiO.lk Blog java Why can't I pass lambda inline into try-with-resources
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

Exit mobile version