Rule 7:Include failure-capture information in detail messages
When exception occurs it prints the stack trace that contains string representation,the result of invoking toString method.this typically has exception’s class name followed by Detailed message. which is used frequently by programmers and SRE for investigation software failure. is the failure is non-reproducabe . it may be difficult or impossible to get more info. so,
the detail message of an exception should capture the failure for subsequent analysis.
How to do this?
To capture a failure, the detail message of an exception should contain the values of all parameters and fields that contributed to the exception.
For example,
the detail message of an IndexOutOfBoundsException should contain the lower bound, the upper bound, and the index value that failed to lie between the bounds
caution: stack traces may be seen by many people in the process of diagnosing and fixing software issues, do not include passwords, encryption keys, and the like in detail messages.
it is not importand to provide too much prose since stack trace has file name and line number that cause the excption(so including variables values will connect the dots) because the stack trace is intended to be used with documentation and sourcecode(if needed).
the DETAIL MESSAGE of exception should not be confused with USER-LEVEL ERROR message , USER-LEVEL ERROR message is excpeted to be intelligible by end user.
User-level error messages are often localized, whereas exception detail messages rarely are.
One way to ensure that a exception contain adequate FAILURE-CAPTURE INFORMATION is to REQUIRE “DETAIL MESSAGE” in constructor instead of toString.
Example:
instead of a String constructor, IndexOutOfBoundsException could have had a constructor that looks like this: /**
- Constructs an IndexOutOfBoundsException.
* - @param lowerBound the lowest legal index value
- @param upperBound the highest legal index value plus one
- @param index the actual index value
*/
public IndexOutOfBoundsException(int lowerBound, int upperBound,
int index) {
// Generate a detail message that captures the failure
super(String.format(
“Lower bound: %d, Upper bound: %d, Index: %d”,
lowerBound, upperBound, index));
// Save failure information for programmatic access
this.lowerBound = lowerBound;
this.upperBound = upperBound;
this.index = index;
}
As of Java 9, IndexOutOfBoundsException finally acquired a constructor that takes an int valued index parameter, but sadly it omits the lowerBound and upperBound parameters.
SO while designign custom exception you must have consutrctor varient with detail message.