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?
A finally block always executes, regardless of whether an exception is thrown.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With