ExecutionException Cause Chain

Unwrap checked failures from concurrent tasks with ExecutionException.getCause, restoring the original exception instead of wrapping it in another layer.

JavaResilience

Code

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

public class TaskErrorBridge {

    static String loadLicense(String key) throws Exception {
        if (!key.startsWith("lic-")) {
            // 受检异常:任务内部无法直接抛过 Callable 边界
            throw new Exception("invalid license key: " + key);
        }
        return "activated:" + key;
    }

    public static void main(String[] args) {
        ExecutorService pool = Executors.newSingleThreadExecutor();
        try {
            Future<String> done = pool.submit(() -> loadLicense("wrong-key"));
            done.get();
        } catch (ExecutionException wrapper) {
            // getCause 还原任务内原始异常:类型与消息都不变
            Throwable cause = wrapper.getCause();
            System.out.println("cause type: " + cause.getClass().getSimpleName());
            System.out.println("cause msg:  " + cause.getMessage());
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } finally {
            pool.shutdown();
        }
    }
}

How the snippet works

The snippet is organized around the class TaskErrorBridge and the function main.

Invalid states are rejected up front: it throws Exception instead of continuing with bad data.

Watch out for

  • Zero third-party dependencies — the runtime provides every API used here.

Putting it to use

Entry signature: public static void main(String[] args)

The demo output is labeled (cause type:, cause msg:), so every printed line maps back to its originating operation.

Core lines

ExecutorService pool = Executors.newSingleThreadExecutor();
throw new Exception("invalid license key: " + key);
Thread.currentThread().interrupt();

Interactive Tools for This Topic

FAQ

What happens on invalid input?
The code refuses to continue: `Exception` is thrown while the state is still recoverable.
What does ExecutionException Cause Chain print when run?
No setup needed: run the file and look for labeled lines like `cause type:`, `cause msg:` in the output.