Effective Java 61 Throw exceptions appropriate to the abstraction
Exception translation: higher layers should catch lower-level exceptions and, in their place, throw exceptions that can be explained in terms of the higher-level abstraction.
// Exception Translation
try {
// Use lower-level abstraction to do our bidding
...
} catch(LowerLevelException e) {
throw new HigherLevelException(...);
}
Example
/**
* 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) {
throw new IndexOutOfBoundsException("Index: " + index);
}
}
ExceptionChain: The lower-level exception (the cause) is passed to the higher-level exception, which provides an accessor method (Throwable.getCause ) to retrieve the lower-level exception:
// Exception Chaining
try {
... // Use lower-level abstraction to do our bidding
} catch (LowerLevelException cause) {
throw new HigherLevelException( cause);
}
// Exception with chaining-aware constructor
class HigherLevelException extends Exception {
HigherLevelException(Throwable cause) {
super(cause);
}
}
Note
Most standard exceptions have chaining-aware constructors. For exceptions that don't, you can set the cause using Throwable's initCause method. Not only does exception chaining let you access the cause programmatically (with getCause ), but it integrates the cause's stack trace into that of the higher-level exception.
Principle
While exception translation is superior to mindless propagation of exceptions from lower layers, it should not be overused.
Solutions:
- The best way to deal with exceptions from lower layers is to avoid them by checking the validity of the higher-level method's parameters before passing them on to lower layers.
- The next best thing is to have the higher layer silently work around these exceptions, insulating the caller of the higher-level method from lower-level problems.(Log the exception using some appropriate logging facility such as java.util.logging which allows an administrator to investigate the problem, while insulating the client code and the end user from it.
Summary
If it isn't feasible to prevent or to handle exceptions from lower layers, use exception translation, unless the lower-level method happens to guarantee that all of its exceptions are appropriate to the higher level. Chaining provides the best of both worlds: it allows you to throw an appropriate higher-level exception, while capturing the underlying cause for failure analysis (Item 63).
Effective Java 61 Throw exceptions appropriate to the abstraction的更多相关文章
- Effective Java 57 Use exceptions only for exceptional conditions
Principle Exceptions are, as their name implies, to be used only for exceptional conditions; they sh ...
- Effective Java Index
Hi guys, I am happy to tell you that I am moving to the open source world. And Java is the 1st langu ...
- 《Effective Java》读书笔记 - 9.异常
Chapter 9 Exceptions Item 57: Use exceptions only for exceptional conditions 这条item的意思就是,千万不要用except ...
- Effective Java 目录
<Effective Java>目录摘抄. 我知道这看起来很糟糕.当下,自己缺少实际操作,只能暂时摘抄下目录.随着,实践的增多,慢慢填充更多的示例. Chapter 2 Creating ...
- 【Effective Java】阅读
Java写了很多年,很惭愧,直到最近才读了这本经典之作<Effective Java>,按自己的理解总结下,有些可能还不够深刻 一.Creating and Destroying Obje ...
- Effective Java通俗理解(下)
Effective Java通俗理解(上) 第31条:用实例域代替序数 枚举类型有一个ordinal方法,它范围该常量的序数从0开始,不建议使用这个方法,因为这不能很好地对枚举进行维护,正确应该是利用 ...
- Effective Java 第三版——29. 优先考虑泛型
Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...
- Effective Java —— try-with-resources 优先于 try-finally
本文参考 本篇文章参考自<Effective Java>第三版第九条"Prefer try-with-resources to try-finally" The cod ...
- Effective java笔记(二),所有对象的通用方法
Object类的所有非final方法(equals.hashCode.toString.clone.finalize)都要遵守通用约定(general contract),否则其它依赖于这些约定的类( ...
随机推荐
- VM不能连入局域网
如果选了Host-only,那么虚拟机与跑虚拟机的宿主就无法连通了. 可以选用Bridged模式,那么虚拟机与跑虚拟机的主机连通了
- WebService基于SoapHeader实现安全认证
本文仅提供通过设置SoapHeader来控制非法用户对WebService的调用,如果是WebService建议使用WSE3.0来保护Web服务,如果使用的是Viaual Studio 2008可以使 ...
- 通过LINQ表达式树动态构建查询条件
第一种方法: public static class PredicateExtensions { public static Expression<Func<T, bool>> ...
- servlet、filter、listener、interceptor之间的区别和联系
一.概念 1.servlet:servlet是一种运行服务器端的java应用程序,具有独立于平台和协议的特性,并且可以动态的生成web页面,它工作在客户端请求与服务器响应的中间层. 2.filter: ...
- 【UWP】对 Thickness 类型属性进行动画
好几个月没写 blog 了,一个是在忙新版的碧影壁纸,另一方面是等(观望)周年更新的 api(不过现在还是比较失望,仍然没法支持矩形以外的 Clip).闲话少说,进入主题. 在 UWP 中,出于性能考 ...
- javaScript一些函数--Math()
1.不能显式地创建一个Math对象,直接使用它就可以了: 2.Math对象不能存储数据,和String,Date对象不同: 3.前面知道了parseInt()函数会通过消去小数点后面的一切,来使一个小 ...
- Winform开发框架之权限管理系统改进的经验总结(4)--用户分级管理
在实际的系统应用环境中,用户的分级管理一般也是比较常见的功能,小的业务系统可以不需要,但是一般涉及到集团.分子公司.或者是事业单位里面的各个处室或者某某局的人员管理,这些分级管理就显得比较必要,否则单 ...
- c++容器(vector、list、deque)
vector ,deque 和 list 顺序性容器: 向量 vector : 是一个线性顺序结构.相当于数组,但其大小可以不预先指定,并且自动扩展.它可以像数组一样被操作,由于它的特性我们完全可 ...
- 重新想象 Windows 8 Store Apps (43) - 多线程之任务: Task 基础, 多任务并行执行, 并行运算(Parallel)
[源码下载] 重新想象 Windows 8 Store Apps (43) - 多线程之任务: Task 基础, 多任务并行执行, 并行运算(Parallel) 作者:webabcd 介绍重新想象 W ...
- Ahjesus获取自定义属性Attribute或属性的名称
1:设置自己的自定义属性 public class NameAttribute:Attribute { private string _description; public NameAttribut ...