Guava的异常工具类--Throwables

Guava为我们提供了一个非常方便并且实用的异常处理工具类:Throwables类。

这个类的API可以参见:http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/base/Throwables.html

这个类的官方英文简述:https://code.google.com/p/guava-libraries/wiki/ThrowablesExplained

下面是本人的一些简要总结:

 

我们在日常的开发中遇到异常的时候,往往需要做下面的几件事情中的一些:

1. 将异常信息存入数据库、日志文件、或者邮件等。

2. 将受检查的异常转换为运行时异常

3. 在代码中得到引发异常的最低层异常

4. 得到异常链

5. 过滤异常,只抛出感兴趣的异常

而借助于Guava的Throwables,我们可以很方便的做到这些:

以list的方式得到throwable的异常链:

1
static  List<Throwable> getCausalChain(Throwable throwable)

  

返回最底层的异常

1
static  Throwable getRootCause(Throwable throwable)

 

返回printStackTrace的结果string
 

1
static  String getStackTraceAsString(Throwable throwable)

把受检查的异常转换为运行时异常:

1
public  static  RuntimeException propagate(Throwable throwable)

只抛出感兴趣的异常:

1
2
public  static  <X  extends  Throwable>  void  propagateIfInstanceOf(
       @Nullable  Throwable throwable, Class<X> declaredType)  throws  X

下面用官网的例子说大致说一下吧:

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

  上面的例子中,只抛出感兴趣的IOException或者SQLException,至于其他的异常直接转换为运行时异常。

1
2
3
4
5
6
7
8
try  {
     someMethodThatCouldThrowAnything();
   catch  (IKnowWhatToDoWithThisException e) {
     handle(e);
   catch  (Throwable t) {
     Throwables.propagateIfPossible(t);
     throw  new  RuntimeException( "unexpected" , t);
   }

  propagateIfPossible方法只会对RuntimeException或者Error异常感兴趣

1
2
3
4
5
6
7
8
try  {
      someMethodThatCouldThrowAnything();
    catch  (IKnowWhatToDoWithThisException e) {
      handle(e);
    catch  (Throwable t) {
      Throwables.propagateIfPossible(t, OtherException. class );
      throw  new  RuntimeException( "unexpected" , t);
    }

  propagateIfPossible的另外一个重载方法,容许我们来自己指定一个感兴趣的异常。这样这个方法只会对RuntimeException或者Error和我们指定的这3种异常感兴趣。

1
2
3
4
5
6
7
8
9
T doSomething() {
      try  {
        return  someMethodThatCouldThrowAnything();
      catch  (IKnowWhatToDoWithThisException e) {
        return  handle(e);
      catch  (Throwable t) {
        throw  Throwables.propagate(t);
      }
    }

  上面的方法会将受检查的异常转换为运行时异常。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值