If I am catching exceptions separately then why do I need to make the value final ? for e.g. 1. Is this considered a good practice ? If yes why ? If not why ?
catch(final InputOutputException exception)
{// do stuff
}
If I am catching exceptions separately then why do I need to make the value final ? for e.g. 1. Is this considered a good practice ? If yes why ? If not why ?
catch(final InputOutputException exception)
{// do stuff
}
In Java anything can be declared final
- in this case the declaration is akin to declaring a method parameter final
.
The effect of this is that you won't be able to reassign the value
catch(final InputOutputException ex) {
ex = new InputOutputException();
// ^ compile time error.
}
In practice I have only really ever seen this used if the Exception
needs to be used in an anonymous class, as only final
local variables are allowed to be referenced in this way:
} catch (final Exception e) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
myLabel.setText(e.getMessage());
}
});
}
Robert Simmons Jr in his book Hardcore Java recommends making everything final
. The justification for this is that it turns typos and code bugs into compile time errors.
Making it final
makes it clear that you haven't changed the field.
IMHO If your handling code is not so short and simple that the reader cannot work this out easily you have done something wrong.
I think you should make fields final
as classes can be long, but methods should be simple enough you can work out whether they are final or not.