Pass all relevant data to Exceptions in Java

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 true only if aNumber is in the range
  * aLow..aHigh (inclusive).
  *
  * @param aLow less than or equal to aHigh.
  */
  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

0 comments: