Why should you place close() calls in a finally block when working with JDBC resources?

Get ready for your Object‑Oriented Programming Test. Use flashcards and multiple-choice questions. Each question includes hints and explanations. Prepare for your exam today!

Multiple Choice

Why should you place close() calls in a finally block when working with JDBC resources?

Explanation:
Releasing database resources reliably requires closing them in a finally block. When you work with JDBC, resources such as a Connection, a Statement, or a ResultSet consume scarce system and database resources. If you close them only after the normal path completes, an exception thrown inside the try block can skip that closing step, leaving resources open and potentially exhausting the pool or causing leaks. Placing the close() calls in a finally block ensures they run no matter what happened in the try block, so resources are released promptly and consistently. Relying on garbage collection isn’t appropriate here because GC timing is unpredictable and won’t guarantee timely release of native resources like database connections. While the option about reducing code size isn’t the goal, and performance isn’t the primary reason, the real benefit is correctness and reliability of resource cleanup. In modern code, try-with-resources offers a cleaner way to achieve the same effect automatically.

Releasing database resources reliably requires closing them in a finally block. When you work with JDBC, resources such as a Connection, a Statement, or a ResultSet consume scarce system and database resources. If you close them only after the normal path completes, an exception thrown inside the try block can skip that closing step, leaving resources open and potentially exhausting the pool or causing leaks. Placing the close() calls in a finally block ensures they run no matter what happened in the try block, so resources are released promptly and consistently.

Relying on garbage collection isn’t appropriate here because GC timing is unpredictable and won’t guarantee timely release of native resources like database connections. While the option about reducing code size isn’t the goal, and performance isn’t the primary reason, the real benefit is correctness and reliability of resource cleanup. In modern code, try-with-resources offers a cleaner way to achieve the same effect automatically.

Subscribe

Get the latest from Examzify

You can unsubscribe at any time. Read our privacy policy