Bird
0
0

You need to write a Java method that safely closes a resource like a file or database connection. Which is the best practice?

hard📝 Application Q9 of 15
Java - Custom Exceptions
You need to write a Java method that safely closes a resource like a file or database connection. Which is the best practice?
AClose the resource only if no exceptions occur
BUse try-finally block to close the resource
CUse try-with-resources statement to auto-close the resource
DIgnore closing the resource to improve performance
Step-by-Step Solution
Solution:
  1. Step 1: Understand resource management in Java

    Try-with-resources automatically closes resources even if exceptions occur.
  2. Step 2: Compare with other options

    Try-finally works but is more verbose. Ignoring closing causes resource leaks.
  3. Final Answer:

    Use try-with-resources statement to auto-close the resource -> Option C
  4. Quick Check:

    Try-with-resources is best for safe resource closing [OK]
Quick Trick: Use try-with-resources for automatic resource management [OK]
Common Mistakes:
  • Forgetting to close resources
  • Using try-finally instead of try-with-resources
  • Closing resources only on no exceptions

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes