当我添加一个抛出异常来运行或初始化时,我有一个错误,上面写着:
ray.java:115: error run() in xray cannot implement run() in Runnable
public void run() throws Exception(
^
overriden method does not throw Exception
1 error
Run Code Online (Sandbox Code Playgroud)
我需要尝试{..} catch来获取URL工作.try {...} catch需要抛出异常的作品.
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
}
Run Code Online (Sandbox Code Playgroud)
你一般可以做的是相反的(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();
}
Run Code Online (Sandbox Code Playgroud)
要解决您的实现问题,您必须捕获并处理异常(漂亮的解决方案)或将其包装到运行时异常中(不太好,但有时会完成).运行时异常不需要在方法签名中声明:
class Foo implements Runnable {
@Override
public void run() {
try {
} catch (Exception e) {
// either handle it properly if you can, or ...
throw new RuntimeException(e);
}
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
213 次 |
最近记录: |