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