mirror of
https://github.com/sjsdfg/effective-java-3rd-chinese.git
synced 2025-03-03 13:50:57 +08:00
update
This commit is contained in:
parent
76dc10da45
commit
9073be121c
@ -7,9 +7,9 @@
|
||||
```java
|
||||
/* Exception Translation */
|
||||
try {
|
||||
... /* Use lower-level abstraction to do our bidding */
|
||||
... /* Use lower-level abstraction to do our bidding */
|
||||
} catch ( LowerLevelException e ) {
|
||||
throw new HigherLevelException(...);
|
||||
throw new HigherLevelException(...);
|
||||
}
|
||||
```
|
||||
|
||||
@ -22,12 +22,12 @@ try {
|
||||
* ({@code index < 0 || index >= size()}).
|
||||
*/
|
||||
public E get( int index ) {
|
||||
ListIterator<E> i = listIterator( index );
|
||||
try {
|
||||
return(i.next() );
|
||||
} catch ( NoSuchElementException e ) {
|
||||
throw new IndexOutOfBoundsException( "Index: " + index );
|
||||
}
|
||||
ListIterator<E> i = listIterator( index );
|
||||
try {
|
||||
return(i.next() );
|
||||
} catch ( NoSuchElementException e ) {
|
||||
throw new IndexOutOfBoundsException( "Index: " + index );
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
@ -47,15 +47,15 @@ throw new HigherLevelException(cause);
|
||||
```java
|
||||
/* Exception with chaining-aware constructor */
|
||||
class HigherLevelException extends Exception {
|
||||
HigherLevelException( Throwable cause ) {
|
||||
super(cause);
|
||||
}
|
||||
HigherLevelException( Throwable cause ) {
|
||||
super(cause);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
大多数标准的异常都有支持链的构造器。对于没有支持链的异常,可以利用 Throwable 的 initCause 方法设置原因。异常链不仅让你可以通过程序(用 getCause) 访问原因,还可以将原因的堆战轨迹集成到更高层的异常中。
|
||||
|
||||
**尽管异常转译与不加选择地从低层传递异常的做法相比有所改进,但是也不能滥用它。**如有可能,处理来自低层异常的最好做法是,在调用低层方法之前确保它们会成功执行,从而避免它们抛出异常。有时候,可以在给低层传递参数之前,检查更高层方法的参数的有效性,从而避免低层方法抛出异常。
|
||||
**尽管异常转译与不加选择地从低层传递异常的做法相比有所改进,但是也不能滥用它。** 如有可能,处理来自低层异常的最好做法是,在调用低层方法之前确保它们会成功执行,从而避免它们抛出异常。有时候,可以在给低层传递参数之前,检查更高层方法的参数的有效性,从而避免低层方法抛出异常。
|
||||
|
||||
如果无法阻止来自低层的异常,其次的做法是,让更高层来悄悄地处理这些异常,从而将高层方法的调用者与低层的问题隔离开来。在这种情况下,可以用某种适当的记录机制(如 java.util.logging) 将异常记录下来。这样有助于管理员调查问题,同时又将客户端代码和最终用户与问题隔离开来。
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user