aspose file tools*
The moose likes JDBC and the fly likes Connection Objects & Scope Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Databases » JDBC
Bookmark "Connection Objects & Scope" Watch "Connection Objects & Scope" New topic

Connection Objects & Scope

Elam Daly

Joined: Aug 09, 2003
Posts: 16
Hi all,

I'm doing the Sun JDBC tutorial and am confused on something.
If I declare a Connection object outside of a try/catch block, shouldn't the connection be valid outside of the try/catch block in which it is actually initialized?

I'm getting a 'variable con might not have been initialized' error. Does this mean that I have to enclose everything in a giant try/catch block?
The code works if I put the 'con=DriverManger.getConnection( url )' inside of the 2nd try block, but that can't be efficient. Opening a connection everytime to do a query?


[ June 18, 2004: Message edited by: elam daly ]
[ June 18, 2004: Message edited by: elam daly ]
Blake Minghelli
Ranch Hand

Joined: Sep 13, 2002
Posts: 331
'variable con might not have been initialized'

The variable con is accessible outside of the try/catch but the compiler is smart enough to recognize that it is possible that con might never be assigned a value, not even null. Local variables are not automatically null like instance variables.
The easiest thing to address that is to change


The difference is subtle but this ensures that con is definitely assigned some value before it is used again, and therefore makes the compiler happy.

Blake Minghelli<br />SCWCD<br /> <br />"I'd put a quote here but I'm a non-conformist"
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
subject: Connection Objects & Scope
Similar Threads
No Suitible Driver Error
ClassNotFoundException generated!
Class.forName() for drive using Oracle 8i
a easy question please help !!!
Error in connection