【问题标题】:How do I declare an exception in an anonymous thread?如何在匿名线程中声明异常?
【发布时间】:2011-09-26 18:54:17
【问题描述】:
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 {
                    ^

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

【问题讨论】:

  • 您希望您的程序如何处理异常?
  • @SomeBloke,实现 Runnable 并将其传递给线程而不是子类化线程被认为是最佳实践。

标签: java sockets exception runnable


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

        改用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 抛出的任何异常。

        【讨论】:

          【解决方案5】:

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

          【讨论】:

            【解决方案6】:

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

            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();
            

            【讨论】:

              猜你喜欢
              • 2013-06-05
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2012-11-19
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多