java - 为什么我收到一条错误消息说没有抛出任何异常?

标签 java multithreading exception netbeans executor

我在实现 Callable 的类中有这个:

public class MasterCrawler implements Callable {
    public Object call() throws SQLException {
        resumeCrawling();
        return true;
    }
    //more code with methods that throws an SQLException
}

在执行这个 Callable 的其他类中,是这样的:

MasterCrawler crawler = new MasterCrawler();
try{
    executorService.submit(crawler); //crawler is the class that implements Callable
}(catch SQLException){
    //do something here
}

但是我收到了一个错误,IDE 的消息是永远不会抛出 SQLException。这是因为我在 ExecutorService 中执行?

更新:因此提交不会抛出 SQLException。我该怎么做才能执行 Callable(作为线程运行)并捕获异常?

已解决:

public class MasterCrawler implements Callable {
    @Override
    public Object call() throws Exception {
        try {
            resumeCrawling();
            return true;
        } catch (SQLException sqle) {
            return sqle;            
        }
     }
}


Future resC = es.submit(masterCrawler);
if (resC.get(5, TimeUnit.SECONDS) instanceof SQLException) {
    //do something here
}

最佳答案

当您调用submit 时,您传递的是一个对象。您没有调用 call()

编辑

提交 返回 Future F。当您调用 f.get() 时,该方法会抛出 ExecutionException。如果在可调用对象的执行过程中遇到问题。如果是这样,它将包含 call() 抛出的异常。

通过将 Callable 提交给执行程序,您实际上是在要求它(异步)执行它。无需采取进一步行动。只需检索 future 并等待。

关于解决方案

虽然您的解决方案可行,但这段代码不是很干净,因为您劫持了 Call 的返回值。尝试这样的事情:

public class MasterCrawler implements Callable<Void> {

    @Override
    public Void call() throws SQLException {
        resumeCrawling();
        return null;
    }

    public void resumeCrawling() throws SQLException {
        // ... if there is a problem
        throw new SQLException();
    }    

}

public void doIt() {

    ExecutorService es = Executors.newCachedThreadPool();
    Future<Void> resC = es.submit(new MasterCrawler());

    try {

        resC.get(5, TimeUnit.SECONDS);
        // Success

    } catch ( ExecutionException ex ) {

        SQLException se = (SQLException) ex.getCause();
        // Do something with the exception

    } catch ( TimeoutException ex ) {

        // Execution timed-out

    } catch ( InterruptedException ex ) {

        // Execution was interrupted

    } 

}

关于java - 为什么我收到一条错误消息说没有抛出任何异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6147085/

相关文章:

java - 如果刷新 token 被撤销,则从应用程序中注销用户

ruby-on-rails - ActiveRecord::Batches::find_each 线程安全吗?

python - 没有括号的 "raise exception()"和 "raise exception"有区别吗?

java - 如何将图片添加到我自己的图库

JavaFX。将辅助方法中的实例变量更改为启动方法

c# - 安全使用 'HttpContext.Current.Cache'

java - 具有多个线程的 ExecutorService 无法正常工作,但在 Debug模式下工作正常

c++ - 如何记录 C++ 异常

shell - ArangoDB 异常

java - 访问内部类中的局部变量