主要推荐
在异常消息中详细说明失败情况:
- 包括导致失败的参数和字段的值。
- 使用简洁且信息丰富的消息来帮助分析。
- 示例:对于 indexoutofboundsexception,包括:
throw new indexoutofboundsexception("index: " + index + ", lower bound: " + lowerbound + ", upper bound: " + upperbound);
避免包含敏感数据:
- 切勿在详细消息中泄露密码、加密密钥或敏感信息,因为堆栈跟踪可以被多人查看。
优先考虑内容而不是可读性:
- 详细信息应该针对开发者和工程师,协助故障分析。
- 向最终用户发送的消息应该是单独且友好的,必要时进行本地化。
特定的构建者优势
- 特定于异常的构造函数有助于捕获相关信息并自动生成消息。
- 减少错误并确保捕获失败的一致性。
- 理想构造函数的示例:
public class indexoutofboundsexception extends runtimeexception {
private final int lowerbound;
private final int upperbound;
private final int index;
public indexoutofboundsexception(int lowerbound, int upperbound, int index) {
super("index: " + index + ", lower bound: " + lowerbound + ", upper bound: " + upperbound);
this.lowerbound = lowerbound;
this.upperbound = upperbound;
this.index = index;
}
public int getlowerbound() {
return lowerbound;
}
public int getupperbound() {
return upperbound;
}
public int getindex() {
return index;
}
}
包含访问失败详细信息的方法
- 对于受检查的异常,getter 可以方便恢复和分析。
- 即使对于未检查的异常,也建议在适当的情况下提供 getter。
最佳实践
- 将消息逻辑置于异常类中:
- 避免在代码中的多个点重复详细的消息生成逻辑。
- 集中式消息生成示例:
public class divisionbyzeroexception extends arithmeticexception {
private final int numerator;
public divisionbyzeroexception(int numerator) {
super("attempted to divide " + numerator + " by zero.");
this.numerator = numerator;
}
public int getnumerator() {
return numerator;
}
}
真实案例
indexoutofboundsexception 示例(java 9 ):
public indexoutofboundsexception(int index) {
super("index out of range: " + index);
}
自定义类示例:
public class InvalidConfigurationException extends RuntimeException {
private final String configKey;
public InvalidConfigurationException(String configKey) {
super("Invalid configuration for key: " + configKey);
this.configKey = configKey;
}
public String getConfigKey() {
return configKey;
}
}
结论
- 始终在异常消息中包含相关的失败信息,避免敏感数据。
- 使用特定的构造函数和访问方法来捕获和记录关键信息。
- 这些做法提高了可靠性,并使代码更易于调试和维护。
书中的示例:










