2
InputStream in = ClientSocket.getInputStream();
new Thread()
{
    public void run() {
        while (true)
        {
            int i = in.read();
            handleInput(i);
        }
    }
}.start();

我正在使用此代码在套接字上收听新数据并获得:

FaceNetChat.java:37: unreported exception java.io.IOException; must be caught or declared to be thrown
                int i = in.read();
                               ^

当我在“ run() ”之后添加“ throws IOException ”时,我得到:

FaceNetChat.java:34: run() in  cannot implement run() in java.lang.Runnable; overridden method does not throw java.io.IOException
        public void run() throws IOException {
                    ^

这可能很简单,但我不知所措。我如何通过这个?

4

6 回答 6

5

您不能覆盖不会引发异常的Runnable.run()接口。您必须改为在 run 方法中处理异常。

try {
  int i = in.read();
} catch (IOException e) {
  // do something that makes sense for your application
}
于 2011-07-01T13:47:34.437 回答
1

改用java.util.concurrent.Callable<V>

    final Callable<Integer> callable = new Callable<Integer>() {

        @Override
        public Integer call() throws Exception {
            ... code that can throw a checked exception ...
        }
    };
    final ExecutorService executor = Executors.newSingleThreadExecutor();
    final Future<Integer> future = executor.submit(callable);
    try {
        future.get();
    } finally {
        executor.shutdown();
    }

当你想处理Callable. 它会抛出任何抛出的异常Callable

于 2011-07-01T14:00:38.207 回答
1

你不能 - 中的run()方法Thread根本不能抛出未经检查的异常。这实际上与匿名类没有任何关系——如果你尝试Thread直接扩展,你会得到同样的结果。

当异常发生时,你需要弄清楚你想要发生什么。你想让它杀死线程吗?以某种方式被举报?考虑使用未经检查的异常、顶级处理程序等。

于 2011-07-01T13:48:51.583 回答
1

您不能“通过”异常,因为此代码在不同的线程中运行。会在哪里抓到?异常不是异步事件,它们是一种流控制结构。您可以在 run 方法中尝试/捕获它。

于 2011-07-01T13:51:35.617 回答
0

您是否尝试过使用 try/catch?您可能只是因为没有恒定的流进入而得到该异常。

于 2011-07-01T13:49:23.407 回答
0

您需要处理异常或作为未经检查的异常重新抛出。

InputStream in = ClientSocket.getInputStream();
new Thread() {
  public void run() {
    try {
      while (true) {
        int i = in.read();
        handleInput(i);
      }
    } catch (IOException iox) {
      // handle, log or wrap in runtime exception
    }
  }
}.start();
于 2011-07-01T13:50:38.960 回答