0

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 } 
1
  • 1
    You do not need to make anything final per se, but final is a compile time check that you do not reassign a variable in this block. Some / many people like to declare anything which should not be reassigned as final. Commented Oct 28, 2013 at 8:03

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Assigning a RuntimeException to a variable of type InputOutputException would also result in a compile time error if the variable wasn't final.
@MarkRotteveel fair point - have changed the example. It was merely illustrative.
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.