• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

what is finally for

 
Pat Peg
Ranch Hand
Posts: 195
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because I was thinking it was to clean up connections and things. If that is the case can someone explain this error


I get "the local variable connection may not have been initialized" when I try to close my connection in finally. If I try and create a connection outside of try then I also get an error. Can someone put some light on this because it seems a bit illogical.
 
Joel McNary
Bartender
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The problem is that it is theoretically possible that you never assign a value to your connection object.

But, if you set it to null, then the compiler won't complain (although you will have to check for null so you don't get a runtime exception).

 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Look at your code, and remember "finally" is always executed after "try", whether an exception is thrown, or not. Now, imagine that Class.forName() throws an exception. The finally block will then execute. What is the value of "connection" at that point? It's undefined, because it's never been initialized, not even to "null". This is a problem, as Java won't let you access a variable that's never been assigned to. The solution: initialize connection to null when you declare it:

Connection connection = null;

Now the error goes away.

But now there's another problem in the code. Imagine, now, that Class.forName() works but DriverManager.getConnection() doesn't. Now what is the value of connection in the finally block? That's right, it's null. So you have to test for that:

 
Pat Peg
Ranch Hand
Posts: 195
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank is clear now, thanks...
 
Tony Morris
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Don't assign the local (or any local for that matter) to null.
The number of leaks I have found in others' code as a result...

Instead, use an embedded try block.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic