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),否则其它依赖于这些约定的类( ...
随机推荐
- 缓存池扩展 (Buffer Pool Extension)实践
SQL Server 2014缓存池扩展 (Buffer Pool Extension)功能可以将缓存池扩展到较快的SSD存储上.为内存比较紧张的系统提供了新的扩展途径. Buffer Pool 扩展 ...
- 学习android开发笔记
最近重点看了几个android工程的源代码,有几点疑问 1:为什么android客户端游戏要开启n个线程,而且通常每个线程的操作只有i++: 2:为什么很多列表在游戏逻辑和绘制逻辑里没有做同步: 3: ...
- Redis设计与实现-客户端服务端与事件
事件 redis服务器是事件驱动的,事件分为文件事件与时间事件 文件事件是服务器通过套接字与客户端连接,两者之间的通信会产生相应的文件事件,服务器监听并处理这些事件完成网络操作: 时间事件是指redi ...
- Spring基础—— 泛型依赖注入
一.为了更加快捷的开发,为了更少的配置,特别是针对 Web 环境的开发,从 Spring 4.0 之后,Spring 引入了 泛型依赖注入. 二.泛型依赖注入:子类之间的依赖关系由其父类泛型以及父类之 ...
- SQL Server添加MDW性能监控报表
10.2 Data Collector与MDW Data Collection功能是SQL SERVER 2005版本提供的数据库监控报表的功能,通过定时地对数据库的语句运行情况,服务器各种资源的监控 ...
- ASP.NET MVC中错误日志信息记录
MVC中有一个处理异常的过滤器 HandleErrorAttribute 1.新建一个类继承自 HandleErrorAttribute,然后重写OnException这个方法 public clas ...
- MVC学习笔记索引帖
[MVC学习笔记]1.项目结构搭建及单个类在各个层次中的实现 [MVC学习笔记]2.使用T4模板生成其他类的具体实现 [MVC学习笔记]3.使用Spring.Net应用IOC(依赖倒置) [MVC学习 ...
- Winform窗体实现简单的二维码生成和保存
二维码的生成需要用到二维码生成的类库,ThoughtWorks.QRCode.dll 步骤: 第一步:下载二维码生成类库,ThoughtWorks.QRCode.dll 第二步:新建winform项目 ...
- 开源项目Foq简介
Foq是一个轻量级-线程安全的mocking类库.使用它来mock抽象类与接口这是我们通常的做法.Foq的名字来自Moq,如果你使用过Moq的话,自然后联想到它能做什么.Foq主要是为了F#的 ...
- netty Failed to submit an exceptionCaught() event异常
最近测试netty开发的服务端应用在关闭时,出现下列异常: ->###WARN#########nioEventLoopGroup-3-2###io.netty.util.internal.lo ...