java - 如何结合异常来摆脱重复代码?

标签 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;
}

最佳答案

创建一个会抛出异常的方法:

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/

相关文章:

java - 终止 Java 线程

java - 使用动态规划的第 n 个斐波那契数

java - 如何用 do...catch 捕获 NSRangeException?

大 O 分析算法

java - Iterable 的 Java 最轻量级非并发实现是什么?

c - C 中将数组和数组指针传递给函数的区别

Java WeakHashMap 引用未更新

java - 处理java堆空间异常

python - 不可能捕获 asyncio.TimeoutError 吗?

java - 如果传递了错误类型的对象,我应该抛出什么类型的异常?