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.

댓글

이 블로그의 인기 게시물

How to split a list into chunks of 100 items in JavaScript, 자바스크립트 리스트 쪼개기

Install and run an FTP server using Docker