我在实现 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/