What change should you make to apply good coding practices to this fragment?
A.
Add nested try-with-resources statements for the statement and ResultSet declarations.
B.
Add the statement and ResultSet declarations to the try-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 evenif an unexpected exception occurs. But finally is useful for more than just exception
handling — it allows theprogrammer 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 areanticipated.
Should be B (or A).
I think it’s B
I’d always pick A.
Why? Because there might be more code needed to create the Statement / ResultSet.
Also, if I pick A, I have more fine-grained control over the exceptions I can catch from using Statement and ResultSet (if I’d pick B, I could catch an SQLException, but what did it occur on? On a ResultSet, or a Statement, or a Connection?).
C because I can put a rollback if a unexpected exception occurs, try with resources only execute a close.
If you want to put rollback, you need catch.
C says “Add a finally” not a catch.
I would pick B.
Nope, the conn, stmt and rs variables in this example will be out of scope by the time execution reaches the catch or finally!
C