zoukankan      html  css  js  c++  java
  • Guava学习笔记(5)Throwables简化异常处理

    有时候, 我们需要捕获异常, 你想要传递异常到下一个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
  • 相关阅读:
    第九周作业
    第八周作业
    第七周作业
    作业2
    作业1
    2019春总结作业
    第十四周总结
    十二周编程总结
    十一周编程总结
    第十周作业
  • 原文地址:https://www.cnblogs.com/icejoywoo/p/2723468.html
Copyright © 2011-2022 走看看