Java ErrorsLesson 48Free preview
Java try-with-resources
This lesson is part of Java · All levels
Summary
Try-with-resources is a feature of Java 7 that closes the resource automatically at the end of the try block. Resource is sufficiently declared in the try box, so you don't have to write the manual in the finally. This way minimizes the leakage of the handle file and makes the code more neat.
Key points
- Syntax: try (Resource r = new Resource()) {...} with resource declared right after try
- Resource must implement the AutoCloseable interface (owned by method close() throws Exception)
- Close() is automatically called, including when the block try to throw exception
- If there is more than one resource, the closure is reversed (LIFO, last resource closed first)
- You can add the catch block and finally like a regular try-catch
Full lesson
Code examples and quizzes
Full lessons, code examples, and quizzes are available to subscribers. 5 questions.