相关疑难解决方法(0)

抛出异常的Java 8 Lambda函数?

我知道如何创建对具有String参数并返回一个方法的方法的引用int,它是:

Function<String, Integer>
Run Code Online (Sandbox Code Playgroud)

但是,如果函数抛出异常,这不起作用,比如说定义为:

Integer myMethod(String s) throws IOException
Run Code Online (Sandbox Code Playgroud)

我该如何定义这个参考?

java lambda java-8

438
推荐指数
14
解决办法
28万
查看次数

JDK8 CompletableFuture.supplyAsync如何处理interruptedException

CompletableFuture.supplyAsync(
() -> {
    transporter.write(req);
    //here take the value from a blocking queue,will throw a interruptedException
    return responseQueue.take();
},  executorService);
Run Code Online (Sandbox Code Playgroud)

处理interruptedException的常用方法是再次中断或直接抛出interruptedException,但两者都无法工作.有人有想法吗?

java lambda exception java-8

14
推荐指数
2
解决办法
2万
查看次数

使用CompletableFuture处理Java 8供应商异常

考虑以下代码 -

public class TestCompletableFuture {

    BiConsumer<Integer, Throwable> biConsumer = (x,y) -> {
        System.out.println(x);
        System.out.println(y);
    };

    public static void main(String args[]) {
        TestCompletableFuture testF = new TestCompletableFuture();
        testF.start();      
    }

    public void start() {
        Supplier<Integer> numberSupplier = new Supplier<Integer>() {
            @Override
            public Integer get() {
                return SupplyNumbers.sendNumbers();                     
            }
        };
        CompletableFuture<Integer> testFuture = CompletableFuture.supplyAsync(numberSupplier).whenComplete(biConsumer);         
    }       
}

class SupplyNumbers {
    public static Integer sendNumbers(){
        return 25; // just for working sake its not  correct.
    }
}
Run Code Online (Sandbox Code Playgroud)

以上的事情很好.但是sendNumbers也可以在我的情况下抛出一个检查过的异常,例如:

class SupplyNumbers {
    public …
Run Code Online (Sandbox Code Playgroud)

java exception java-8 completable-future

7
推荐指数
3
解决办法
1万
查看次数

使用 CompletableFuture 抛出已检查的异常

Stackoverflow 包含多个有关将检查异常与CompletableFuture.

这里有一些例子:

虽然一些答案暗示使用CompletableFuture.completeExceptionally()他们的方法会导致用户代码难以阅读。

我将利用这个空间提供一个替代解决方案,以提高可读性。

请注意,这个问题特定于 CompletableFuture。这使我们能够提供不更普遍地扩展到 lambda 表达式的解决方案。

java completable-future

5
推荐指数
1
解决办法
5028
查看次数

标签 统计

java ×4

java-8 ×3

completable-future ×2

exception ×2

lambda ×2