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.

댓글

이 블로그의 인기 게시물

PYTHONPATH, Python 모듈 환경설정

You can use Sublime Text from the command line by utilizing the subl command

git 명령어

[gRPC] server of Java and client of Typescript

[Ubuntu] Apache2.4.x 설치

Create topic on Kafka with partition count, 카프카 토픽 생성하기

리눅스의 부팅과정 (프로세스, 서비스 관리)

Auto-populate a calendar in an MUI (Material-UI) TextField component

The pierce selector in Puppeteer