我在一个实现 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
}