Runnable.run()
不會引發檢查異常。因此,您不能執行run() throws Exception
,因爲它會通過投擲違反合同意外的例外。
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);
}
}
}
閱讀概念委託錯誤。 –