Forums Register Login

what is finally for

+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
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).

+Pie Number of slices to send: Send
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:

+Pie Number of slices to send: Send
Thank is clear now, thanks...
+Pie Number of slices to send: Send
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.

Look! I laid an egg! Why does it smell like that? Tiny ad, does this smell weird to you?
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 661 times.
Similar Threads
finally block is not executing
LoginBean doesn't compile
Error in class level variable
About good exception handling practices?
Runtime - NullPointerException
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 16, 2024 08:44:39.