相关疑难解决方法(0)

处理ExecutionException的最佳方法是什么?

我有一个方法,通过超时执行一些任务.我使用ExecutorServer.submit()来获取Future对象,然后使用超时调用future.get().这工作正常,但我的问题是处理我的任务可以抛出的已检查异常的最佳方法.以下代码有效,并保留已检查的异常,但如果方法签名中的已检查异常列表发生更改,则它似乎非常笨拙且容易中断.

对于如何解决这个问题,有任何的建议吗?我需要针对Java 5,但我也很想知道在较新版本的Java中是否有好的解决方案.

public static byte[] doSomethingWithTimeout( int timeout ) throws ProcessExecutionException, InterruptedException, IOException, TimeoutException {

    Callable<byte[]> callable = new Callable<byte[]>() {
        public byte[] call() throws IOException, InterruptedException, ProcessExecutionException {
            //Do some work that could throw one of these exceptions
            return null;
        }
    };

    try {
        ExecutorService service = Executors.newSingleThreadExecutor();
        try {
            Future<byte[]> future = service.submit( callable );
            return future.get( timeout, TimeUnit.MILLISECONDS );
        } finally {
            service.shutdown();
        }
    } catch( Throwable t ) { //Exception handling of nested exceptions is …
Run Code Online (Sandbox Code Playgroud)

java future executorservice executionexception

38
推荐指数
1
解决办法
4万
查看次数