Java CountDownLatch.await() 抛出异常"not compatible with throws clause in Runnable.run()"



我实现了自己的Runnable.run(),它告诉我捕获InterruptedException。然后我添加了

private final CountDownLatch start = new CountDownLatch(1);
private final int eCount = ...;
public void run(){
for(int e = 0;e<eCount;++e){
new Thread(new Runnable()
{
@Override
public void run() throws InterruptedException{
start.await(); // 
}
}).start();
}

但是现在编译错误是:

Exception InterruptedException is not compatible with throws clause in Runnable.run()Java(67109266)

"不兼容抛出子句"是什么意思?如何解决这个问题?

接口Runnable公开了这个方法:

public abstract void run();

此方法不抛出任何异常(只抛出未检查的异常)。

你得到的消息意味着你不能在这个方法中抛出检查异常(如InterruptedException),否则,它不匹配run()签名。

一般来说,如果你@Override一个接口/抽象类的方法,你有必要尊重它强加的签名,这包括throws列表(如果你愿意,你不能抛出一个声明的异常,但你不能抛出一个没有声明的异常)。

关于如何修复,您可以将已检查异常包装在未检查异常中:
@Override
public void run() {
try {
start.await();
} catch (InterruptedException e) { //<-- catch the checked exception
throw new RuntimeException("Interrupted", e); //<-- wrap it into an unchecked exception (you can also create your own, which I suggest, instead of using the generic RuntimeException)
}
}

最新更新