Compilation fails for JDK 11 and compiles fine for JDK 8

淺唱寂寞╮ 提交于 2019-12-05 06:25:35

Because slight updates to the spec say so, probably. Does it matter? It's not going to work like this.

There is no real purpose to turning the exception thrown into a parameterized type here. Also, youll make quite the chain of RuntimeException with this code. Try this, instead:

static <T, R> Function<T, R> wrap(FunException<T, R> fn) {
    return t -> {
        try {
            return fn.apply(t);
        } catch (Error | RuntimeException ex) {
            throw ex;
        } catch (Throwable throwable) {
            throw new RuntimeException("Checked exception in lambda", throwable);
        }
    };
}

interface FunException<T, R> {
    R apply(T t) throws Throwable;
}

and now it'll compile fine.

TO THE READER: Don't do this. The correct way to deal with java's rules such as checked exceptions is to deal with them. Using hacks to get around the essence of a language just means your code is non-idiomatic (others who read your code won't get it, and you'll have a hard time reading the code of others. That's bad), tends to interop with other libraries in a bad way, and various features that are supposed to help, now hurt (example: Here you get a LOT of causal exception chains which make the reading of your logs and exception traces more difficult than is needed). Also, being 'off the beaten path' this far leads to fun times such as code that used to compile no longer compiling.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!