What change should you make to apply good coding practices to this fragment?

Given the code fragment:

What change should you make to apply good coding practices to this fragment?

Given the code fragment:

What change should you make to apply good coding practices to this fragment?

A.
Add nested try-with-resources statements for the statement and Resulset declarations.

B.
Add the statement and Resulset declarations to the cry-with-resources statement.

C.
Add a finally clause after the catch clause.

D.
Rethrow SQLException.

Explanation:
The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.



Leave a Reply 12

Your email address will not be published. Required fields are marked *


Charlie

Charlie

In my opinion B is the best answer.

hafid

hafid

Answer : B
All A, B, C and D are correct answers
but it’s “good coding practices” to regroup connection, statement and resultset in one try-with-resources statement

Serg

Serg

I think “A” in modification:
A. Move in nested try-with-resources statements for the statement and Resulset declarations.

B. – try-with-resources have Statment and ResultSet declarations.

C. – is Correct, if use try-catch without resources.

Tim

Tim

Not sure about A and B, but would vote for B. However as hafid’s words, ABCD are all correct modifications.