Wednesday, February 16, 2011

Pass all pertinent data to exceptions

When an exception occurs, it is important that all pertinent data be passed to the exception's constructor. Such data is often critical for understanding and solving the problem, and can greatly reduce the time needed to find a solution.

The this reference is sometimes useful for this purpose, since toString is implicitly called. In addition, if you are defining exception classes yourself, you may even design your constructors to force the caller to pass the pertinent data.

Uninformative stack traces are very frustrating for the maintainer, and often inspire even the most well-tempered programmers to temporarily violate local community standards for obscenity.

Example

public final class RangeChecker {
  /**
  * Return <code>true</code> only if <code>aNumber</code> is in the range
  * <code>aLow..aHigh</code> (inclusive).
  *
  * @param <code>aLow</code> less than or equal to <code>aHigh</code>.
  */
  static public boolean isInRange( int aNumber, int aLow, int aHigh ){
    if (aLow > aHigh) {
      throw new IllegalArgumentException("Low:" + aLow + " greater than High:" + aHigh);
    }
    return (aLow <= aNumber && aNumber <= aHigh);
  }
} 

Effective Java mentions IndexOutOfBoundsException as a counter-example. This exception does not provide information regarding the relevant indexes, which would often be useful for solving the problem :


  • the offending index value
  • the minimum and maximum permitted index values

No comments:

Post a Comment

Chitika