Asynchrone Programmierung mit Java, handle and exceptionally

avatar

Auch in der asynchronen Programmierung ist eine Fehlerbehandlung sinnvoll. Dazu gibt es zwei Möglichkeiten. Mit handle kann neben den Fehler auch noch ein Wert zurückgegeben werden. Mit exceptionally ist dies nicht der Fall und wird verwendet falls kein Rückgabewert erwartet wird.

import java.util.concurrent.CompletableFuture;

public class Asynchron {

    /** in case an exception occurs inside an async function.
     *  handle: expect the result and the error message
     *  exceptionally: expect the error message only
     */
    public void exceptionHandlingAsync() {
        boolean flag = false;
        CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(
            () -> {
                if(!flag) return 1/0;
                return -1;
            }
        ).exceptionally(
            (error) -> {
                System.out.println(error.getMessage());
                return -1;
            }
        );
        System.out.println(future1.join());

        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(
            () -> {
                if(flag) return 1/0;
                return 1;
            }
        ).handle(
            (arg, error) -> {
                if(error != null){
                    System.out.println(error.getMessage());
                    return -1;
                }
                return arg;
            }
        );
        System.out.println(future2.join());
    }
    
    public static void main(String[] args){
        Asynchron async = new Asynchron();
        async.exceptionHandlingAsync();
    }
}

java_async3.png



0
0
0.000
0 comments