• Post Reply Bookmark Topic Watch Topic
  • New Topic

try/catch inside finally  RSS feed

 
Anuj Kalra
Greenhorn
Posts: 10
Java Oracle Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Hello everyone!
This is my first post here:

So i was writing a database connectivity code.
I have objects of Connection Interface, ResultSet and PreparedStatement as class data members..
I write all the statements in the try block and give all the necessary catch blocks for my database connectivity.

However after the last catch block i try to write a finally block where I want to close all the objects. But the eclipse compiler is asking me to put the closing code in another try catch block(i.e. inside finally).
Why is this happening??

Here's the code:


Please help!
And guys this is my first post here.. If i violated any posting rules I am deeply sorry!
 
Campbell Ritchie
Marshal
Posts: 56578
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

The reason there is a complaint about the finally is that the close() methods are declared possibly to throw an SQLException (or similar) which is checked. Examples: 1 2 3. Since those calls are not in a try statement, they must be handled by your method declaring it rethrows that Exception (with a throws clause).
I am rusty with my SQL, but it appears it may only be necessary to close the Connection. You probably should close the connection, unless you are sure it closes automatically. You want a try-finally inside the try.
Of course, if you use Java7+, you are probably better off using a try with resources, because Connection implements AutoCloseable and you can dispense with the finally. If you have any updates or inserts, you should commit or rollback before closing the connection.
 
Campbell Ritchie
Marshal
Posts: 56578
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Earlier, I wrote: . . .
. . .
I rust you noticed the spelling error
 
Stephan van Hulst
Saloon Keeper
Posts: 7993
143
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I partially disagree with you, Campbell. The finally-clause should always terminate normally, without throwing any exceptions, or returning new results. The reason is that if an exceptional situation occurs in the try-clause, it will be hidden by whatever happens in finally. Usually exceptions that occur in finally are not that important anyway (like attempting to close a connection that was already bad), so just log them and continue normal operation (whatever normal was).
Of course, as you said, this is much more elegant with try-with-resources.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!