How to catch exceptions on Future in Java, 자바 Future 에러 잡기

In Java, catching exceptions in a Future object is slightly different from catching exceptions in regular synchronous code. A Future represents the result of an asynchronous computation. If an exception is thrown during the asynchronous task execution, it will be captured and rethrown when you try to retrieve the result using the get() method.

Here's how to catch an exception in a Future:

Example using Future and ExecutorService:

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class FutureExceptionHandling {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newSingleThreadExecutor();

        // Submit a Callable task that throws an exception
        Future<Integer> future = executor.submit(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                throw new Exception("Something went wrong!");
            }
        });

        try {
            // Retrieve the result, this will throw ExecutionException if an exception occurred
            Integer result = future.get();
        } catch (ExecutionException e) {
            // The actual cause of the exception is wrapped inside the ExecutionException
            System.out.println("Caught exception: " + e.getCause().getMessage());
        } catch (InterruptedException e) {
            // Handle the case where the thread was interrupted
            System.out.println("Thread was interrupted.");
        } finally {
            executor.shutdown();
        }
    }
}

Key points:

  1. ExecutionException: This exception is thrown by the get() method when the computation in the background task threw an exception. The actual exception that was thrown is wrapped inside the ExecutionException, which you can access using e.getCause().
  2. InterruptedException: This is thrown if the thread is interrupted while waiting for the result.

In the example, we submit a Callable task to an ExecutorService. The task throws an exception, and when we call future.get(), it rethrows the exception wrapped inside an ExecutionException, which we handle.

댓글

이 블로그의 인기 게시물

Develop a Kafka producer to send messages to a Kafka topic

Using the MinIO API via curl

max_active_runs of Airflow

Boilerplate for typescript server programing

difference between truncate and truncate_preserve in hbase

What are 5 creative things I could do with my kids' art, 아이와 함께하는 창의적 놀이

Parasite of korean movie

Kafka consumer in a Spring Boot application using a scheduled task

To integrate Spring Boot with your gRPC service using Gradle, Java, and Avro

kafka polling vs listen