java关于throw Exception的一个小秘密

136 阅读1分钟

简介

之前的文章我们讲到,在stream中处理异常,需要将checked exception转换为unchecked exception来处理。

我们是这样做的:

static <T> Consumer<T> consumerWrapper(
        ThrowingConsumer<T, Exception> throwingConsumer) {

    return i -> {
        try {
            throwingConsumer.accept(i);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    };
}

将异常捕获,然后封装成为RuntimeException。

封装成RuntimeException感觉总是有那么一点点问题,那么有没有什么更好的办法? throw小诀窍

java的类型推断大家应该都知道,如果是 这样的形式,那么T将会被认为是RuntimeException!

我们看下例子:

public class RethrowException {

    public static <T extends Exception, R> R throwException(Exception t) throws T {
        throw (T) t; // just throw it, convert checked exception to unchecked exception
    }

}

上面的类中,我们定义了一个throwException方法,接收一个Exception参数,将其转换为T,这里的T就是unchecked exception。

接下来看下具体的使用:

@Slf4j
public class RethrowUsage {

    public static void main(String[] args) {
        try {
            throwIOException();
        } catch (IOException e) {
           log.error(e.getMessage(),e);
            RethrowException.throwException(e);
        }
    }

    static void throwIOException() throws IOException{
        throw new IOException("io exception");
    }
}

上面的例子中,我们将一个IOException转换成了一个unchecked exception。 总结

本文介绍了一种特殊的异常转换的例子,大家可以参考一下。

只要一步一个脚印,水滴石穿,吃透、搞懂、拿捏住是完全没有问题的!看到这里的都是妥妥的铁粉无疑了,底下是微信,找到的可是有大把源码,学习路线思维导图啥的,多的我就不透露,539413949看大家自己的积极性了啊,热爱所热爱的,学习伴随终生