Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close connection and statement finally

Which is better for finally block:

finally {
        try {
            con.close();
            stat.close();
        } catch (SQLException sqlee) {
            sqlee.printStackTrace();
        }
    }

Or:

finally {
        try {
            if (con != null) {
                con.close();
            }
            if (stat != null) {
                stat.close();
            }
        } catch (SQLException sqlee) {
            sqlee.printStackTrace();
        }
    }
like image 993
Sajad Avatar asked Aug 07 '13 22:08

Sajad


People also ask

Does closing connection close statement?

Yes it does, Connection. close API says "Releases this Connection object's database and JDBC resources immediately instead of waiting for them to be automatically released".

What is the finally statement?

The finally block in java is used to put important codes such as clean up code e.g. closing the file or closing the connection. The finally block executes whether exception rise or not and whether exception handled or not. A finally contains all the crucial statements regardless of the exception occurs or not.

What is the use of finally?

The finally keyword is used to execute code (used with exceptions - try.. catch statements) no matter if there is an exception or not.

What is try finally statement?

The finally block is a place to put any code that must execute, whether the try-block raised an exception or not. The syntax of the try-finally statement is this − try: You do your operations here; ...................... Due to any exception, this may be skipped.


1 Answers

Better way to use is the 2nd one, because if an exception is thrown while initializing con or stat, they won't be initialized, and might be left initialized to null. In that case, using the 1st code will throw NullPointerException.

Also, if you are already on Java 7, you should consider using try-with-resources, which automatically closes the resources. From the linked tutorial:

The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

like image 104
Rohit Jain Avatar answered Oct 05 '22 08:10

Rohit Jain