Pass all pertinent data to exceptions

When an exception occurs, it's 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 have been known to inspire unpleasant cursing.

Example


public final class RangeChecker {

  /**
  * Return <tt>true</tt> only if <tt>aNumber</tt> is in the range
  * <tt>aLow..aHigh</tt> (inclusive).
  *
  * @param <tt>aLow</tt> less than or equal to <tt>aHigh</tt>.
  */
  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:
Would you use this technique?
Yes   No   Undecided   
© 2014 Hirondelle Systems | Source Code | Contact | License | RSS
Individual code snippets can be used under this BSD license - Last updated on September 21, 2013.
Over 2,000,000 unique IPs last year - Built with WEB4J.
- In Memoriam : Bill Dirani -