Bird
0
0

How can you ensure a resource like a file or database connection is closed even if an exception occurs?

hard📝 Application Q9 of 15
Java - Exception Handling
How can you ensure a resource like a file or database connection is closed even if an exception occurs?
AClose resource before opening it
BClose resource only if no exception occurs
CUse try-with-resources or finally block to close the resource
DIgnore closing resources to avoid errors
Step-by-Step Solution
Solution:
  1. Step 1: Understand resource management in Java

    Resources must be closed to avoid leaks, even if exceptions happen.
  2. Step 2: Use try-with-resources or finally block

    These ensure resource closure regardless of exceptions.
  3. Final Answer:

    Use try-with-resources or finally block to close the resource -> Option C
  4. Quick Check:

    Resource closure guaranteed by finally or try-with-resources [OK]
Quick Trick: Use finally or try-with-resources to close resources [OK]
Common Mistakes:
  • Closing resources only on success
  • Ignoring resource closure
  • Closing resource before use

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes