有时候, 我们需要捕获异常, 你想要传递异常到下一个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 }
参考文献: