【Java】Java 异常与Guava Throwables 类

Java中的异常

1、异常类有两个主要的子类:IOException 类和 RuntimeException 类 ,其中RuntimeException 也叫非检查异常,其他的是受检查异常,也就是如果方法声明一个受检查异常,必须try-catch 或者再抛出

2、Java7 的多重捕获

try {
            File file = new File("/tmp");
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write("hello".getBytes(Charset.forName("utf8")));
        } catch (NullPointerException |IOException e) {
            log.error(Throwables.getStackTraceAsString(e));
        }catch (Exception e) {
           throw  new RuntimeException("未知异常"); 
        }

Guava Throwables

主要方法说明
1、RuntimeException propagate(Throwable)

如果 Throwable 是 Error 或 RuntimeException,直接抛出;否则把 Throwable 包装成 RuntimeException 抛出。

2、void propagateIfPossible( Throwable, Class) throws X
如果 Throwable 类型为 X, Error 或 RuntimeException 才抛出

3、void propagateIfInstanceOf( Throwable, Class) throws X
Throwable 类型为 X 才抛出

posted @ 2019-05-17 16:09  加州水果  阅读(239)  评论(0编辑  收藏  举报