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.

댓글

이 블로그의 인기 게시물

Creating an synchronous HTTP request using Spring RestTemplate

동남아 국가들이 사용하는 언어

형태소 분석 태그

MySQL GRANT

max_active_runs of Airflow

Screenshot of a web page using Puppeteer, 웹페이지 스크린샷

how to delete all issues on project in sentry, 센트리 이슈 삭제하기

Using the MinIO API via curl

Read a file in Java, 자바 파일 읽기

dagrun_timeout of Airflow