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. Android 学习笔记之Volley开源框架解析(二)

    PS:Volley已经学完,可以安心的写一下博客总结一下了... 学习内容: 1.Request的完整封装... 2.RetryPolicy,DefaultRetryPolicy(请求重试策略源码解析 ...

  2. 如何将oc代码转换成运行时代码

    // 运行时 其实就是oc的底层  平时写的代码 最终都是转成底层的运行时代码以下面程序为例子: 如果我们想要看我们的main.m文件底层转换成了怎样的运行时代码 ,我们可以这样做. 1.打开终端  ...

  3. 利用DropDownList实现下拉

    在视图的Model<Vo>里面我们需要使用IEnumerable来将别的列表的数据全部的转化为下拉列表.下面是关于在项目中实际的写法. 一:实现下拉属性列表的写法   通过使用Select ...

  4. C#设计模式——访问者模式(Visitor Pattern)

    一.概述由于需求的改变,某些类常常需要增加新的功能,但由于种种原因这些类层次必须保持稳定,不允许开发人员随意修改.对此,访问者模式可以在不更改类层次结构的前提下透明的为各个类动态添加新的功能.二.访问 ...

  5. 【C#】OOP之多态那点事

    前言: 对菜鸟开发者的忠告:花一万个小时练习 Coding,不要浪费一万小时无谓地 Debugging(也就说看代码) 看上面的UML图,我们创建一个抽象的Instrument类,类中有一个抽象方法p ...

  6. 创建一个弹出DIV窗口

    创建一个弹出DIV窗口 摘自:   http://www.cnblogs.com/TivonStone/archive/2012/03/20/2407919.html 创建一个弹出DIV窗口可能是现在 ...

  7. Verilog学习笔记简单功能实现(三)...............同步有限状态机

    在Verilog中可以采用多种方法来描述有限状态机最常见的方法就是用always和case语句.如下图所示的状态转移图就表示了一个简单的有限状态机: 图中:图表示了一个四状态的状态机,输入为A和Res ...

  8. CentOS常用指令

    创建文件: 如touch a.txt 创建文件夹: mkdir -p 文件夹名,当文件夹不存在时候,创建这个文件夹 文件重命名: 把文件text.php得命名为index.php,可以是rename ...

  9. java入门基础知识点总结

    JavaScript他是一种描述性语言,其实他并不难学,只要用心学,一定会学好,我相信大家在看这篇文章的时候,一定也学过HTML吧,使用JavaScript就是为了能和网页有更好的交互,下面切入主题. ...

  10. 【背景建模】VIBE

    ViBe是一种像素级的背景建模.前景检测算法,该算法主要不同之处是背景模型的更新策略,随机选择需要替换的像素的样本,随机选择邻域像素进行更新.在无法确定像素变化的模型时,随机的更新策略,在一定程度上可 ...