为什么我得到一个错误,说没有人抛出异常?

问题描述:

我有这个在实现可调用的类:为什么我得到一个错误,说没有人抛出异常?

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

在这种执行该赎回,像这样其他类:

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

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

UPDATE:所以提交不会抛出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 
} 
+0

Callable引发异常。 http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Callable.html – 2011-05-27 02:34:32

当您致电submit时,您正在传递一个对象。你不叫call()

EDIT

Submit返回Future F。当您致电f.get()时,如果在执行可调用期间遇到问题,该方法可能会触发ExecutionException。如果是这样,它将包含call()抛出的异常。

通过将您的Callable提交给执行者,实际上是要求它执行它(异步)。无需采取进一步行动。只要找回未来并等待。

有关解决方案

虽然你的解决方案将工作,这不是很干净的代码,因为你劫持调用的返回值。试试这样的:

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 

    } 

} 
+0

如何获取调用方法抛出的异常? – 2011-05-27 02:09:14

+1

@ditkin不,这不是正确的方法,因为如果你想通知调用者/调用者,捕获调用中的异常不会告诉你如何将它传递给调用者/调用者。你需要让未来抓住它。 – JVerstry 2011-05-27 02:22:06

+0

我在呼叫方法内引发异常并将其返回,并对IF产生威胁。看起来有点奇怪,我会找到另一种方式,但现在,解决我的问题。 – 2011-05-27 03:00:45

的提交方法不抛出SQLException。

这是因为SQLException永远不会被抓取工具抛出。

尝试使用finally而不是catch,看看你是否会遇到问题或工作。

+0

不,这根本无济于事......而且,如果没有首先抓住。 – JVerstry 2011-05-27 02:20:08

+0

等等...我可以,我经常这样做。如果您不希望在此步骤的代码中使用捕获异常,但可以在更全局的范围内执行此操作。 – 2011-05-27 02:26:42

你在用什么IDE?当我尝试你的代码时,Eclipse会抱怨“未处理的异常类型异常”。这很有意义,因为Callable接口定义了call()方法来抛出Exception。仅仅因为你的实现类声明了一个更受限制的异常类型,调用程序就不能指望它。它期望你能抓住异常。