Runnable.run()
不抛出检查异常。因此,您无法实施run() throws Exception
,因为它会通过抛出意外异常来破坏合同。Runnable
interface Runnable {
// guarantees no checked exception is thrown
public void run();
}
class Foo implements Runnable {
@Override
public void run() throws Exception {} // violates the guarantee
}
您通常可以做的是相反的事情(但不适用于Runnable
):
interface Foo {
// Exception might be thrown, but does not have to
public void bar() throws Exception;
}
class FooImpl implements Foo {
// FooImpl does not throw exception, so you can omit
// the throws; it does not hurt if consumer expect an
// exception that is never thrown
@Override
public void bar();
}
要解决您的实现问题,您要么必须捕获并处理异常(很好的解决方案),要么将其包装到运行时异常中(不太好,但不时完成)。运行时异常不需要在方法签名中声明:
class Foo implements Runnable {
@Override
public void run() {
try {
} catch (Exception e) {
// either handle it properly if you can, or ...
throw new RuntimeException(e);
}
}
}