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:

  1. 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.
  2. 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的更多相关文章

  1. 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 ...

  2. 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 ...

  3. 《Effective Java》读书笔记 - 9.异常

    Chapter 9 Exceptions Item 57: Use exceptions only for exceptional conditions 这条item的意思就是,千万不要用except ...

  4. Effective Java 目录

    <Effective Java>目录摘抄. 我知道这看起来很糟糕.当下,自己缺少实际操作,只能暂时摘抄下目录.随着,实践的增多,慢慢填充更多的示例. Chapter 2 Creating ...

  5. 【Effective Java】阅读

    Java写了很多年,很惭愧,直到最近才读了这本经典之作<Effective Java>,按自己的理解总结下,有些可能还不够深刻 一.Creating and Destroying Obje ...

  6. Effective Java通俗理解(下)

    Effective Java通俗理解(上) 第31条:用实例域代替序数 枚举类型有一个ordinal方法,它范围该常量的序数从0开始,不建议使用这个方法,因为这不能很好地对枚举进行维护,正确应该是利用 ...

  7. Effective Java 第三版——29. 优先考虑泛型

    Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...

  8. Effective Java —— try-with-resources 优先于 try-finally

    本文参考 本篇文章参考自<Effective Java>第三版第九条"Prefer try-with-resources to try-finally" The cod ...

  9. Effective java笔记(二),所有对象的通用方法

    Object类的所有非final方法(equals.hashCode.toString.clone.finalize)都要遵守通用约定(general contract),否则其它依赖于这些约定的类( ...

随机推荐

  1. java io系列15之 DataOutputStream(数据输出流)的认知、源码和示例

    本章介绍DataOutputStream.我们先对DataOutputStream有个大致认识,然后再深入学习它的源码,最后通过示例加深对它的了解. 转载请注明出处:http://www.cnblog ...

  2. Mysql学习笔记(十三)权限管理

    学习内容: 1.权限管理: 关于mysql的权限简单的理解就是mysql允许你做你权利以内的事情,不可以越界.比如只允许你执行select操作,那么你就不能执行update操作.只允许你从某台机器上连 ...

  3. (9)分布式下的爬虫Scrapy应该如何做-关于ajax抓取的处理(一)

    转载请注明出处:http://www.cnblogs.com/codefish/p/4993809.html 最近在群里频繁的被问到ajax和js的处理问题,我们都知道,现在很多的页面都是用动态加载的 ...

  4. Winform里面的缓存使用

    缓存在很多情况下需要用到,合理利用缓存可以一方面可以提高程序的响应速度,同时可以减少对特定资源访问的压力.本文主要针对自己在Winform方面的缓存使用做一个引导性的介绍,希望大家能够从中了解一些缓存 ...

  5. 正则表达式相关:C# 抓取网页类(获取网页中所有信息)

    类的代码: using System; using System.Data; using System.Configuration; using System.Net; using System.IO ...

  6. 重新想象 Windows 8 Store Apps (40) - 剪切板: 复制/粘贴文本, html, 图片, 文件

    [源码下载] 重新想象 Windows 8 Store Apps (40) - 剪切板: 复制/粘贴文本, html, 图片, 文件 作者:webabcd 介绍重新想象 Windows 8 Store ...

  7. 雷军V5,米3横空出世

    小米3 下午两点,小米CEO:雷军(也是一个传奇人物),虽然没购买门票,只是自己一个人看微博,看新闻,还是了解到了小米3的面貌,这次雷哥还给大家带来了MITV,售价¥2999!(无法相信)顶配.这次我 ...

  8. 重大发现Discuz DB层跨库映射关系表名前缀BUG

    本文更新:http://www.cnblogs.com/x3d/p/3916198.html 场景: 在Discuz中创建Table模型,但该Table所在库与Discuz不在同一个库. Discuz ...

  9. php中的字符串常用函数(四) ord() 获得字符的ascii码 chr()获取ascii码对应的字符

    ord('a');//=>97 返回小写a 的ascii码值97 chr(97);//=>a 返回ascii码表上的97对应的 小写a

  10. jsp页面 列表 展示 ajax异步实现

    1. 服务端先返回页面基本结构(如message.jsp), <%@ page language="java" contentType="text/html; ch ...