I have this in a class that implements Callable :
public class MasterCrawler implements Callable {
public Object call() throws SQLException {
resumeCrawling();
return true;
}
//more code with methods that throws an SQLException
}
In other class that execute this Callable, something like this:
MasterCrawler crawler = new MasterCrawler();
try{
executorService.submit(crawler); //crawler is the class that implements Callable
}(catch SQLException){
//do something here
}
But I got an error and a message of the IDE that an SQLException is never throw. This is because I’m executing in a ExecutorService?
UPDATE: So the submit don’t throws an SQLException. How I can do to execute the Callable (run as thread) and catch the exception?
SOLVED:
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
}
When you call
submit, you are passing an object. You are not callingcall().EDIT
Submitreturns a Future f. When you callf.get(), the method can throw an ExecutionException if a problem is encountered during the execution of the callable. If so, it will contain the exception thrown bycall().By submitting your Callable to the executor, you are actually asking it to execute it (asynchronously). No need for further action. Just retrieve the future and wait.
ABOUT THE SOLUTION
Although your solution will work, this not very clean code, because you are hijacking the return value of Call. Try something like this: