如何替代重复的单个try/catch语句?优化邻域平面查找代码
优化方案解析
当然有优化这段冗余代码的方案,将try/catch逻辑封装到函数中是可行的优化方向,不过还有更高效的替代方案,以下是具体实现:
方案一:封装try/catch到工具方法
把重复的"尝试获取元素并添加到邻域列表"逻辑抽成独立方法,直接调用即可消除冗余代码:
// 封装的工具方法 private void addNeighborIfExists(List<?> items, int targetIndex, List<Plane> neighborPlanes) { try { neighborPlanes.add((Plane) items.get(targetIndex)); } catch (IndexOutOfBoundsException ignored) { // 忽略越界异常,不做任何处理 } } // 调用优化后的代码 addNeighborIfExists(items, index - rowLength, neighborPlanes); // 上方 addNeighborIfExists(items, index - rowLength - 1, neighborPlanes); // 左上方 addNeighborIfExists(items, index - rowLength + 1, neighborPlanes); // 右上方 addNeighborIfExists(items, index - 1, neighborPlanes); // 左侧 addNeighborIfExists(items, index + 1, neighborPlanes); // 右侧 addNeighborIfExists(items, index + rowLength, neighborPlanes); // 下方 addNeighborIfExists(items, index + rowLength - 1, neighborPlanes); // 左下方 addNeighborIfExists(items, index + rowLength + 1, neighborPlanes); // 右下方
这种方式直接消除了重复的try/catch块,代码结构更简洁,可读性也更强。
方案二:提前判断索引合法性(更优)
异常设计的初衷是处理意外情况,而边缘位置的索引越界是可预见的场景,用条件判断提前验证索引合法性,不仅能避免冗余,还能减少异常处理的性能开销:
int totalItems = items.size(); // 计算当前元素的行、列位置 int currentRow = index / rowLength; int currentCol = index % rowLength; // 定义8个邻域的行、列偏移量 int[][] neighborOffsets = { {-1, 0}, {-1, -1}, {-1, 1}, {0, -1}, {0, 1}, {1, 0}, {1, -1}, {1, 1} }; for (int[] offset : neighborOffsets) { int neighborRow = currentRow + offset[0]; int neighborCol = currentCol + offset[1]; // 验证邻域的行、列是否在有效范围内 boolean rowValid = neighborRow >= 0 && neighborRow < (totalItems + rowLength - 1) / rowLength; boolean colValid = neighborCol >= 0 && neighborCol < rowLength; if (rowValid && colValid) { int neighborIndex = neighborRow * rowLength + neighborCol; // 额外验证索引是否未超出列表总长度(兼容最后一行元素不足的情况) if (neighborIndex < totalItems) { neighborPlanes.add((Plane) items.get(neighborIndex)); } } }
这种方案完全摆脱了try/catch依赖,逻辑更直观,性能也更优,尤其在边缘元素较多的场景下优势明显。
总结
- 封装try/catch到函数是有效的冗余消除手段,适合快速优化现有代码;
- 提前判断索引合法性是更推荐的方案,兼顾代码简洁性与运行性能。
内容的提问来源于stack exchange,提问作者DuncanDalas
相关产品推荐
相关产品推荐

