File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes JDBC and Relational Databases and the fly likes Close if SQLException Occured? 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 "Close if SQLException Occured?" Watch "Close if SQLException Occured?" New topic

Close if SQLException Occured?

Gregg Bolinger
GenRocket Founder
Ranch Hand

Joined: Jul 11, 2001
Posts: 15302

If I open a connection to my Database and there was some sort of a problem with the stmt or result set and an SQLException occured, do I need to close the Connection to the Database in the SQLException Block?

Is this correct or is ther another way?
[ February 08, 2002: Message edited by: Gregg Bolinger ]

GenRocket - Experts at Building Test Data
Bosun Bello
Ranch Hand

Joined: Nov 06, 2000
Posts: 1510
You can just check the connection for null before trying to close it.
catch(SQLEXception problem) {
if(connection != null)
...close connection
catch(some exception)

So much trouble in the world -- Bob Marley
Gregg Bolinger
GenRocket Founder
Ranch Hand

Joined: Jul 11, 2001
Posts: 15302

So it's really the same as my code, only I am checking the connection first. Right?
Ok, thanks for the info.
Jamie Robertson
Ranch Hand

Joined: Jul 09, 2001
Posts: 1879

your code looks like the norm(with Bosun's suggestion included in the inner try/catch block).
<unsubstantiated hearsay> Some people use finally blocks, but I've heard there can be some problems with that too</unsubstantiated hearsay> Maybe someone can verify that.
I agree. Here's the link:
subject: Close if SQLException Occured?
It's not a secret anymore!