代码改变世界

Guava学习笔记(5)--Throwables简化异常处理

2012-10-14 22:21  会被淹死的鱼  阅读(666)  评论(0编辑  收藏  举报

有时候, 我们需要捕获异常, 你想要传递异常到下一个try/catch块中. RuntimeException或Error是不强制捕获的.

Guava提供了一些工具类, 可以简单地捕获和重新抛出多个异常.

1    try {
2      someMethodThatCouldThrowAnything();
3    } catch (IKnowWhatToDoWithThisException e) {
4      handle(e);
5    } catch (Throwable t) {
6      Throwables.propagateIfInstanceOf(t, IOException.class);
7      Throwables.propagateIfInstanceOf(t, SQLException.class);
8      throw Throwables.propagate(t);
9    }

简单使用示例

 1 import java.io.IOException;
 2 
 3 import com.google.common.base.Throwables;
 4 
 5 public class Demo {
 6     public static void main(String[] args) throws IOException {
 7         try {
 8             throw new IOException();
 9         } catch (Throwable t) {
10             Throwables.propagateIfInstanceOf(t, IOException.class);
11             throw Throwables.propagate(t);
12         }
13     }
14 }

 

 

参考文献:

  1. 官方文档: http://code.google.com/p/guava-libraries/wiki/ThrowablesExplained