如何尽量减少代码中重复抛异常的代码:
public R get(int index) throws IndexException {
if (!((0 <= index) && (index < this.info.length))) {
throw new IndexException();
}
return this.info[index];
}
public void set(int index, R r) throws IndexException {
if (!((0 <= index) && (index < this.info.length))) {
throw new IndexException();
}
this.info[index] = r;
}
最佳答案
创建一个会抛出异常的方法:
private void checkBounds(int index) throws IndexException {
if (index < 0 || index >= info.length) {
throw new IndexException();
}
}
然后你可以调用它:
public R get(int index) throws IndexException {
checkBounds(index);
return this.info[index];
}
public void set(int index, R r) throws IndexException {
checkBounds(index);
this.info[index] = r;
}
关于java - 如何结合异常来摆脱重复代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21716423/