1/20
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced | Call with Kai |
|---|
No analytics yet
Send a link to your students to track their progress
What is try-with-resources in Java?
A try statement that automatically closes resources after use
When was try-with-resources introduced?
Java 7
What is a resource in try-with-resources?
An object that must be closed after use (e.g., files, streams, DB connections)
What interface must a resource implement?
AutoCloseable
Example of AutoCloseable classes
FileInputStream, BufferedReader, Scanner, Connection
Basic syntax of try-with-resources
try(Resource res = …) { code }
What happens to resources after try block?
They are automatically closed
Do we need finally block with try-with-resources?
No, it's optional because closing is automatic
What happens if exception occurs?
Resource is still closed automatically
Can we use multiple resources?
Yes, separated by semicolons
Example with multiple resources
try(r1 = …; r2 = …) { }
Order of closing resources
Closed in reverse order of declaration
Can we catch exceptions in try-with-resources?
Yes, using catch blocks
Can we use finally with try-with-resources?
Yes, but usually not needed
What problem does try-with-resources solve?
Resource leaks (forgetting to close resources)
Difference between try-finally and try-with-resources
try-finally requires manual close; try-with-resources is automatic
What happens if close() throws exception?
It becomes a suppressed exception
What is a suppressed exception?
An exception thrown during resource closing while another exception already exists
How to get suppressed exceptions?
using getSuppressed() method
Can we declare resource outside try?
Yes (since Java 9), if it is effectively final
Example Java 9 syntax
Resource r = …; try(r) { }