Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Edited by sciSpider Java v3.0

...

Code Block
bgColor#FFcccc
class Dimensions {
  private int length;
  private int width;
  private int height;

  public Dimensions(int length, int width, int height) {
    this.length = length;
    this.width = width;
    this.height = height;
  }

  protected int getVolumePackage(int weight) {
    length += 2;
    width  += 2;
    height += 2;
    try {
      if(length <&lt;= 2 || width <&lt;= 2 || height <&lt;= 2 || weight <&lt;= 0 || weight >&gt; 20)
        throw new IllegalArgumentException();
	
        int volume = length * width * height; // 12 * 12 * 12 = 1728
        length -=2; width -= 2; height -= 2; // Revert back
        return volume;
      } catch(Throwable t) { 
        MyExceptionReporter mer = new MyExceptionReporter();
        mer.report(t); // Sanitize 
        return -1; // Non-positive error code
      }	
  }

  public static void main(String[] args) {
    Dimensions d = new Dimensions(10, 10, 10);
    System.out.println(d.getVolumePackage(21)); // Prints -1 (error)
    System.out.println(d.getVolumePackage(19)); // Prints 2744 instead of 1728
  }
}

...

Code Block
bgColor#ccccff
protected int getVolumePackage(int weight) {
  try {
    if(length <&lt;= 0 || width <&lt;= 0 || height <&lt;= 0 || weight <&lt;= 0 || weight >&gt; 20)
      throw new IllegalArgumentException(); // Validate first
    
    length += 2;
    width  += 2;
    height += 2;

    int volume = length * width * height;
    length -=2; width -= 2; height -= 2;
    return volume;
  } catch(Throwable t) { MyExceptionReporter mer = new MyExceptionReporter();
    mer.report(t); // Sanitize 
    return -1;
  }		
}

...

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

References

Wiki Markup
\[[Bloch 08|AA. Java References#Bloch 08]\] Item 64: Strive for failure atomicity

...

EXC06-J. Do not let code throw undeclared checked exceptions      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;13. Exceptional Behavior (EXC)      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;EXC30-J. Do not exit abruptly from a finally block