// Exception Translation try { // Use lower-level abstraction to do our bidding ... } catch(LowerLevelException e) { thrownew HigherLevelException(...); }
更具体的例子在List的方法中
1 2 3 4 5 6 7 8 9 10 11 12 13
/** * Returns the element at the specified position in this list. * @throws IndexOutOfBoundsException if the index is out of range * ({@code index < 0 || index >= size()}). */ public E get(int index){ ListIterator<E> i = listIterator(index); try { return i.next(); } catch(NoSuchElementException e) { thrownew IndexOutOfBoundsException("Index: " + index); } }
这种特殊的异常处理方式被称为”异常链”,但是也不应该过度使用
我们也可以在在上层调用中抛出底层错误的原因
1 2 3 4 5 6
// Exception Chaining try { ... // Use lower-level abstraction to do our bidding } catch (LowerLevelException cause) { thrownew HigherLevelException(cause); }
最好的方式还是尽量在底层避免异常,如果不能处理在考虑”异常链”的方式
Item 62: Document all exceptions thrown by each method