Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 991
deamon Avatar asked Jun 09 '10 08:06

deamon


People also ask

Does finally run if there is no exception?

A finally block always executes, regardless of whether an exception is thrown.

Can we keep the statements after finally block?

After the finally block is executed, the statements following it get control. If the try block exits because of an Exception which is handled by a catch block, first that block executes and then control goes to the finally block. After the finally block is executed the statements following it get control.

How do you prevent finally block from execution?

You cannot skip the execution of the final block. Still if you want to do it forcefully when an exception occurred, the only way is to call the System. exit(0) method, at the end of the catch block which is just before the finally block.

What do you put in a finally block?

The finally block in java is used to put important codes such as clean up code e.g. closing the file or closing the connection. The finally block executes whether exception rise or not and whether exception handled or not. A finally contains all the crucial statements regardless of the exception occurs or not.


2 Answers

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.

like image 159
krock Avatar answered Sep 30 '22 15:09

krock


Since it is a local variable, it will get out of scope anyway. It's nonsense.

If it was an instance variable (member variable) of a long lived object, it could be useful since it otherwise might prevent the garbage collector from disposing the object.

like image 32
aioobe Avatar answered Sep 30 '22 14:09

aioobe