Java,尝试...在init或run中捕获

use*_*574 -4 java url

当我添加一个抛出异常来运行或初始化时,我有一个错误,上面写着:

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需要抛出异常的作品.

Mat*_*eid 8

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)