开发者

How do I declare an exception in an anonymous thread?

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

I'm listening to new data on a socket with this code and get:

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

When I add "throws IOException" after the "run()" I get:

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 {
                    ^

It's probably something simple, but I'm at a loss. How do I get passed this?


You can't override the interface of Runnable.run() which does not throw an exception. You must instead handle the exception in the run method.

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


You can't - the run() method in Thread simply can't throw unchecked exceptions. This really doesn't have anything to do with anonymous classes - you'd get the same thing if you tried to extend Thread directly.

You need to work out what you want to happen when that exception occurs. Do you want it to kill the thread? Be reported somehow? Consider the use of unchecked exceptions, top-level handlers etc.


You can't "pass" the exception, since this code is running in a different thread. Where would it be caught? Exceptions are not asynchronous events, they are a flow control structure. You could try/catch it in the run method.


Use java.util.concurrent.Callable<V> instead:

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

You can call get() on the future when you want to deal with the result of the Callable. It will throw any exception that the Callable threw.


Have you tried using a try/catch? You might be getting that exception simply because there is not a constant stream coming in.


You need to handle the exception or rethrow as an unchecked exception.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜