实现说明
ExecutionException 与原始异常链可以归结为类 TaskErrorBridge和函数 main。
非法状态在入口就被拒绝:抛出 Exception,而不是带着坏数据继续。
使用要点
- 跑完文件,输出里会留下标记——
cause type:、cause msg:。
常见问题
输入非法时会怎样?
代码会拒绝继续:抛出 Exception,此时状态仍可恢复。
运行「ExecutionException 与原始异常链」会打印什么?
运行文件本身,cause type:、cause msg: 这些前缀各对应一段演示逻辑。
核心语句
ExecutorService pool = Executors.newSingleThreadExecutor();
throw new Exception("invalid license key: " + key);
Thread.currentThread().interrupt();
代码示例
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();
}
}
}