Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Intermediate
Jan 29, 2003

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.
Ramneek Handa
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date