devxlogo

Using Finally for I/O And SQL

Using Finally for I/O And SQL

An application’s memory footprint grows over time and may eventually cause the application to crash. There are many things that lead to a slow memory burn. One of these is failure to close file handles and SQL database connections.

 File file = new File(...);try {FileInputStream fis = new FileInputStream( file );..} catch(IOException ioe) {ioe.printStackTrace();}try {Connection conn = ....;Statement ps = conn.prepareStatement();..ResultSet rs = ps.executeQuery();..} catch(SQLException sqle) {sqle.printStackTrace();}

In most cases, it’s simple to add code to close these:

 File file = new File(...);try {FileInputStream fis = new FileInputStream( file );..fis.close();} catch(IOException ioe) {ioe.printStackTrace();}try {Connection conn = ....;Statement ps = conn.prepareStatement();..ResultSet rs = ps.executeQuery();..rs.close();ps.close();conn.close();} catch(SQLException sqle) {sqle.printStackTrace();}

When an exception is thrown, however, the connections will not close.Closing is effective inside the catch block, but there may be multiple catch blocks, which would mean a lot of repeated code.
To solve this problem, use the finally keyword. After a block is executed, such as a for loop, a while loop, or a try-catch, any statement inside the finally { } block will be executed.

 try {} catch(SomeException se) {se.printStackTrace();} finally {// this is executed ALWAYS}

Unfortunately, the finally { } block doesn’t share the same scope as the preceding block, so the code gets more complex. For example:

 File file = new File(...);FileInputStream fis = null;try {fis = new FileInputStream( file );..} catch(IOException ioe) {ioe.printStackTrace();} finally {if(fis != null) {fis.close();}}Connection conn = null;Statement ps = null;ResultSet rs = null;try {conn = ....;ps = conn.prepareStatement();..rs = ps.executeQuery();..} catch(SQLException sqle) {sqle.printStackTrace();} finally {if(rs != null) {rs.close();}if(ps != null) {ps.close();}if(conn != null) {conn.close();}}

The code is now longer and more complex, yet it is also stronger and will not leave file handles and SQL connections hanging around.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist