如何在匿名线程中声明异常?

时间:2011-07-01 13:45:36

标签: java sockets exception runnable

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()”之后添加“抛出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 {
                    ^

这可能很简单,但我很茫然。我如何通过这个?

6 个答案:

答案 0 :(得分:5)

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

try {
  int i = in.read();
} catch (IOException e) {
  // do something that makes sense for your application
}

答案 1 :(得分:1)

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

您需要弄清楚发生异常时您想要发生的事情。你想要它杀死线程吗?不知怎的报道?考虑使用未经检查的异常,顶级处理程序等。

答案 2 :(得分:1)

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

答案 3 :(得分: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的结果时,可以在将来调用get()。它将抛出Callable投掷的任何异常。

答案 4 :(得分:0)

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

答案 5 :(得分: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();