• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Finally Block issue with close methods

 
Joseph Smithern
Ranch Hand
Posts: 89
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 690
Eclipse IDE Firefox Browser Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 49849
70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic