This week's giveaway is in the Beginning Java forum.
We're giving away four copies of Bad Programming Practices 101 (e-book) and have Karl Beecher on-line!
See this thread for details.
Win a copy of Bad Programming Practices 101 (e-book) this week in the Beginning Java forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Connection Objects & Scope  RSS feed

 
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?


Thanks.

[ June 18, 2004: Message edited by: elam daly ]
[ June 18, 2004: Message edited by: elam daly ]
 
Ranch Hand
Posts: 331
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

'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

to

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.
 
Don't destroy the earth! That's where I keep all my stuff! Including this tiny ad:
Why should you try IntelliJ IDEA ?
https://coderanch.com/wiki/696337/IntelliJ-IDEA
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!