1 java exception space-efficiency
如何最小化代码中重复的异常抛出代码:
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;
}
Run Code Online (Sandbox Code Playgroud)
创建一个抛出异常的方法:
private void checkBounds(int index) throws IndexException {
if (index < 0 || index >= info.length) {
throw new IndexException();
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以调用它:
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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
69 次 |
| 最近记录: |