-3

Most of the time a block of code is empty when a piece of code is really missing. So such empty block must be either filled or removed. What is the reason to do so?

How does leaving the block empty affect the compilation?

For example:

for (int i = 0; i< 4; i++) 
{

}


try 
{

}


catch (Exception e) 
{

}
Praveen Dinks
  • 21
  • 1
  • 4

1 Answers1

3

In most cases PMD is alerting you to the fact that your empty block does nothing. Why create a for loop or try block which does nothing? In the case of the Exception catch though, it's technically "valid" to catch an Exception and do nothing in the block, but most of the time it causes problems. PMD wants you to act on this exception.

If the Exception doesn't get acted on you can get more errors down the track as a knock on effect of the first problem which occurred. Example: you catch an IOException but then "eat" the exception and don't let the rest of the program know there was an error.

slipperyseal
  • 2,728
  • 1
  • 13
  • 15
  • I agree to your point..But there is certainly some more effort needed by the compiler in this case rather than going to the next lines of the code..There must be a specific reason why PMD suggests that..Is the time consumption of the compiler the only reason?? – Praveen Dinks May 20 '14 at 04:56
  • 1
    it's nothing to do with performance. As per their own decription." It finds common programming flaws like unused variables, empty catch blocks, unnecessary object creation, and so forth". An empty catch block is a bug (according to PMD anyway). And most of the time it is. Note that with PMD you can suppress errors using annotations if you are sure you wanted to do it that way. – slipperyseal May 20 '14 at 04:59
  • Ok.Thank you for your inputs. – Praveen Dinks May 20 '14 at 05:01
  • 1
    You are using PMD to help you find problems with your code. And it's telling you :) It's a very common scenario with Java where someone puts a catch around some code to "fix it". The Exception doesn't get acted on then you get more errors down the track as a knock on effect of the first problem which occurred. Example: you catch an IOException but then "eat" the exception and don't let the rest of the program know there was an error. – slipperyseal May 20 '14 at 05:05
  • You are absolutely right about the catch block. But could you cite any advantages / disadvantages of leaving the FOR block empty? – Praveen Dinks May 20 '14 at 05:12
  • in your above example. you create a loop which counts 0 to 4 in 'i' but does nothing with i at any stage. What does that loop 'do'? Nothing. But, you can write for loops which effect other variables or call methods. In this case, you would use a semicolon instead of brackets. for (x=0;something();x – slipperyseal May 20 '14 at 05:19
  • Thanks @SlipperySeal.That sounds convincing enough. – Praveen Dinks May 20 '14 at 05:34