Two Laptop Bag
The moose likes Beginning Java and the fly likes what is finally for Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "what is finally for" Watch "what is finally for" New topic

what is finally for

Pat Peg
Ranch Hand

Joined: Feb 04, 2005
Posts: 195
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

Joined: Aug 20, 2001
Posts: 1824

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).

Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

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:

[Jess in Action][AskingGoodQuestions]
Pat Peg
Ranch Hand

Joined: Feb 04, 2005
Posts: 195
Thank is clear now, thanks...
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
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.

Tony Morris
Java Q&A (FAQ, Trivia)
I agree. Here's the link:
subject: what is finally for
jQuery in Action, 3rd edition