主要推荐
在异常消息中详细说明失败情况:
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;
}
}
包含访问
失败详细信息的方法
最佳实践
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;
}
}
结论
书中的示例: