Question
When should a Java developer choose try-with-resources deliberately?
- Choose try-with-resources mainly when you want to postpone validation and fix problems manually later.
- Choose try-with-resources whenever you want the code to look more advanced, even if the design gets less clear.
- Use try-with-resources for files, streams, readers, JDBC handles, and any other AutoCloseable resource.
- Choose try-with-resources only to avoid modeling domain rules explicitly in Java code.
Hint
Think about the production scenario where the choice genuinely improves the code.
Answer and rationale
Correct answer: C. Use try-with-resources for files, streams, readers, JDBC handles, and any other AutoCloseable resource.
Use try-with-resources for files, streams, readers, JDBC handles, and any other AutoCloseable resource. Interviewers often ask this to see whether you can connect the concept to real design decisions.
Track: Java