CompletableFuture的exceptionally

CompletableFuture的exceptionally


代码:

private void test() {
    System.out.println("开始...");

    CompletableFuture.supplyAsync(new Supplier<String>() {
        @Override
        public String get() {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            // 此处故意抛出一个空指针异常。
            // 导致代码处理逻辑转入到exceptionally(new Function<Throwable, String>()
            if (true) {
                throw new NullPointerException();
            }

            System.out.println("返回 zhang");
            return "zhang";
        }
    }).exceptionally(new Function<Throwable, String>() {
        @Override
        public String apply(Throwable throwable) {
            System.out.println("exceptionally - apply " + throwable.toString());
            return "发生异常!";
        }
    }).whenCompleteAsync(new BiConsumer<String, Throwable>() {
        @Override
        public void accept(String s, Throwable throwable) {
            System.out.println("accept : " + s);
        }
    });

    System.out.println("运行至此.");
}


运行输出:

07-12 10:32:26.797 17266-17266/? I/System.out: 开始...
07-12 10:32:26.801 17266-17266/? I/System.out: 运行至此.
07-12 10:32:29.803 17266-17318/zhangphil.test I/System.out: exceptionally - apply :java.util.concurrent.CompletionException: java.lang.NullPointerException
07-12 10:32:29.805 17266-17318/zhangphil.test I/System.out: accept : 发生异常!

上一篇:SQL注入漏洞全接触--入门篇


下一篇:深度剖析ConcurrentHashMap源码