Try-With-Resources in Java Explained
Fast recall
Quick revision
Core answer
AutoCloseable resource as the statement exits, in reverse declaration order. It replaces error-prone manual cleanup. If both the body and closing fail, the body failure stays primary and close failures are suppressed; if only closing fails, that close failure propagates.Whether you know try-with-resources auto-closes AutoCloseable resources and why it replaced manual finally-close
Still writing manual finally blocks to close resources, or not null-checking before close in the old pattern
Mention it also fixes the suppressed-exception problem: a failure in close() no longer hides the original try exception
Interview-ready guide
Interview answer
Try-with-resources automatically closes successfully initialized AutoCloseable resources as the statement exits. Resources close in reverse declaration order, which is useful when later resources depend on earlier ones. It replaced verbose manual finally cleanup and handles competing failures correctly.
If the body and close both throw, the body exception remains primary and close failures are available through getSuppressed. If only close throws, that close exception propagates. Resource declarations in the header cannot be reassigned, and since Java 9 an existing final or effectively final local may be used in the resource list.
Try-With-Resources in Java Explained
Direct Answer
Try-with-resources is a Java 7 language feature that closes each successfully initialized AutoCloseable resource as the statement exits, in reverse declaration order. It replaces error-prone manual cleanup. If both the body and closing fail, the body failure stays primary and close failures are suppressed; if only closing fails, that close failure propagates.
Common Mistakes & Pitfalls
- Still writing manual
finallyclose when try-with-resources would be simpler and safer. - Forgetting the resource must implement
AutoCloseable— otherwise it won't compile in the header. - Assuming close order is declaration order — it's reverse.
- Reassigning the resource variable — try-with-resources resources are effectively final.
Check your understanding
Answer these without looking back at the article.
- What interface must a resource implement to work with try-with-resources?
- Can you declare multiple resources in try-with-resources?
- What are suppressed exceptions in try-with-resources?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.