Meaningless Drivel is fun!
The moose likes JDBC and Relational Databases and the fly likes Finally Block issue with close methods Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Head First Android this week in the Android forum!
JavaRanch » Java Forums » Databases » JDBC and Relational Databases
Bookmark "Finally Block issue with close methods" Watch "Finally Block issue with close methods" New topic
Author

Finally Block issue with close methods

Joseph Smithern
Ranch Hand

Joined: Feb 11, 2006
Posts: 89
In my Tomcat 4.1.27 container I am trying to get the finally block to work where it closes the MySQL database connection. Here is my attempt which will not compile:



The error messages after I try and compile Datafetch.java:


If I take out the finally block the Sevlet compiles and shows data in the web page.
Please advise how I can get the finally block to work with the Database close methods.
Kaydell Leavitt
Ranch Hand

Joined: Nov 18, 2006
Posts: 689

I think that within your finally block you need a second, nested try that has a catch block which just logs any exception. I think that I would even put a try-catch around each of the close() method calls so that if one fails, the other resources will stll be released.

I believe that this would catch any exceptions as a result of calling close(). I believe that whenever you close anything like a connection (or a file), all you can do is try and if there's an error, I don't know what else you can do but just log it.

I believe that before calling each close() method, that you should check that the object that you are about to close is not null so that you don't get a NullException when you're just trying to close everything up.

Kaydell

[ May 21, 2007: Message edited by: Kaydell Leavitt ]
[ May 21, 2007: Message edited by: Kaydell Leavitt ]
Ravinder Rana
Greenhorn

Joined: Dec 07, 2006
Posts: 19
close() method of resultset, statement and connection throws SQLException, so you need to put that also in a try-catch block. Before calling close it's better to check that they are not null, otherwise you will get a NullPointerException. So your finally block should look like this:


Hope this helps.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 43368
    
  32
Ravinder Rana is correct that you need to check for nulls. But I would have two try blocks inside each other. You started off with this:-Now set up two try blocks inside each other, like this:-. . but that won't work until you move the finally. . . then add the if(stmt != null) tests as suggested before.

[edit]Clean up some indenting etc.[/edit]
[ May 28, 2007: Message edited by: Campbell Ritchie ]
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Finally Block issue with close methods
 
It's not a secret anymore!