zoukankan      html  css  js  c++  java
  • 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的异常链:

     static List<Throwable> getCausalChain(Throwable throwable) 
    

      

    返回最底层的异常

      static Throwable getRootCause(Throwable throwable) 
    

    返回printStackTrace的结果string
     

     static String getStackTraceAsString(Throwable throwable) 
    

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

      public static RuntimeException propagate(Throwable throwable)
    

    只抛出感兴趣的异常:

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

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

       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,至于其他的异常直接转换为运行时异常。

     try {
         someMethodThatCouldThrowAnything();
       } catch (IKnowWhatToDoWithThisException e) {
         handle(e);
       } catch (Throwable t) {
         Throwables.propagateIfPossible(t);
         throw new RuntimeException("unexpected", t);
       }
    

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

    try {
         someMethodThatCouldThrowAnything();
       } catch (IKnowWhatToDoWithThisException e) {
         handle(e);
       } catch (Throwable t) {
         Throwables.propagateIfPossible(t, OtherException.class);
         throw new RuntimeException("unexpected", t);
       }
    

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

    T doSomething() {
         try {
           return someMethodThatCouldThrowAnything();
         } catch (IKnowWhatToDoWithThisException e) {
           return handle(e);
         } catch (Throwable t) {
           throw Throwables.propagate(t);
         }
       }
    

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

  • 相关阅读:
    JNDI
    在Tomcat上发布JNDI资源
    使用数据库连接池配置数据源
    JDBC连接数据库
    数据库中的一些概念
    线程池和数据库连接池
    springmvc学习指南 之---第25篇 Spring Bean有三种配置方式
    springmvc学习指南 之---第24篇 国际化问题
    深入刨析tomcat 之---第23篇 聊一下web容器的filter配置和defaultservet
    又一本springmvc学习指南 之---第22篇 springmvc 加载.xml文件的bean标签的过程
  • 原文地址:https://www.cnblogs.com/rollenholt/p/3527645.html
Copyright © 2011-2022 走看看