Guava为我们提供了一个非常方便并且实用的异常处理工具类:Throwables类。
这个类的官方英文简述: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); } } |
上面的方法会将受检查的异常转换为运行时异常。
原文:http://www.cnblogs.com/rollenholt/p/3527645.html