Search code examples
javaexceptionfinally

Set reference = null in finally block?


A colleague of mine sets reference to null in finally blocks. I think this is nonsense.

public Something getSomething() {
    JDBCConnection jdbc=null;
    try {
        jdbc=JDBCManager.getConnection(JDBCTypes.MYSQL);
        ...
    }
    finally {
        JDBCManager.free(jdbc);
        jdbc=null; // <-- Useful or not?
    }
}

What do you think of it?


Solution

  • You are correct, jdbc is a local variable so when the getSomething() method returns jdbc will be out of scope and eligible for garbage collection which is effectively the same as setting it to null. So there is no point in setting a variable to null when it is out of scope in the next line of code.

    It is good practice to limit variables to the smallest scope that is needed, e.g. if you only need a variable inside a for loop then declare it in the for loop and it will be eligible for garbage collection when the code exits the for loop. This, as well as reducing the complexity of your methods reduces the need to even set local variables to null at all and as a benefit your code becomes more modular, easier to read and maintain.