`
leonzhx
  • 浏览: 793504 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Item 63: Include failure-capture information in detail messages

阅读更多

1.  When a program fails due to an uncaught exception, the system automatically prints out the exception’s stack trace. The stack trace contains the exception’s string representation, the result of invoking its toString method. This typically consists of the exception’s class name followed by its detail message.

 

2.  It is critically important that the exception’s toString method return as much information as possible concerning the cause of the failure.

 

3.  To capture the failure, the detail message of an exception should contain the values of all parameters and fields that “contributed to the exception.”

 

4.  One way to ensure that exceptions contain adequate failure-capture information in their detail messages is to require this information in their constructors instead of a string detail message. The detail message can then be generated automatically to include the information:

public IndexOutOfBoundsException(int lowerBound, int upperBound, int index) {
    // Generate a detail message that captures the failure
    super("Lower bound: " + lowerBound + ", Upper bound: " + upperBound + ", Index: " + index);
    // Save failure information for programmatic access
    this.lowerBound = lowerBound;
    this.upperBound = upperBound;
    this.index = index;
}

 

It may be appropriate for an exception to provide accessor methods for its failure-capture information.

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics