gpt4 book ai didi

java异常

转载 作者:行者123 更新时间:2023-12-01 14:59:54 25 4
gpt4 key购买 nike

我有两个java类在不同的线程上运行。一个类(class)连接到互联网,而另一个类(class)则连接到互联网类监视连接状态。我想抛出 IOException 以防类建立连接延迟在读取服务器响应时,同时如果从服务器读取了一些响应,我不想抛出异常。

我想出了这段代码。

我的问题是我想在 NetworkMonitor 类中抛出 IOException ,该异常将被捕获NetworkConnector 类是主类。然而编译器提示未捕获的异常。

  public class NetworkConnector{
//method that connects to the server to send or read data.
public String sendData(String url ,String data){
try{

//start the monitor before we read the serverResponse
new NetworkMonitor().startMonitor();

int read ;
while ((read = inputStream.read()) != -1) {
//read data.
sb.append((char) read);

//monitor if we are reading from Server if not reading count 10 to 0 and throw IoException.
new NetworkMonitor().resetCounter();
}

} catch(IOException ex){
//all IOException should be caught here.
}

}

}

//监视是否发生网络 Activity 的类。

  public class NetworkMonitor implements Runnable {

private final int WAITTIME =10;
private int counter = WAITTIME;


public void run(){
try{

while(counter > 0){
//waiting here
counter--; //decrement counter.
Thread.sleep(1000);
}

//when counter is at zero throw iOexception
throw new IOException("Failed to get server Response");

} catch(InterruptedException e){
System.out.println(e.getMessage());
} catch(IOException e){
//i want to throw the IOEception here since the exception should
//be caught by the networkConnector class not the monitor class but the compiler complains.
// unreported exception java.io.IOException; must be caught or declared to be thrown
throw new IOException(e.getMessage());

//throwing another exception type is okay ===>why cant we throw the same type of exception we caught.
throw new IllegalArgumentException(e.getMessage());
}


}

//reset the counter if called.
public void resetCounter(){
counter = WAITTIME;
}

public void startMonitor(){
Thread t = new Thread(this);
t.start();
}

}

最佳答案

您有一个更基本的问题

  • 一个线程中抛出的异常需要传递给另一个线程。您可以使用 ExecutorService 和 Future 来执行此操作。
  • 要实现超时,您可以使用 ScheduledExecutorService。这将允许您安排延迟且可取消的任务。
  • 一个线程中抛出的异常不会解除阻塞读取。您需要关闭连接才能解除阻止,这将导致 IOException。
  • 一旦准备好这些,您就可以使用 Callable 而不是 Runnable 来引发已检查的异常。

而不是睡1秒,睡10次。你可以睡 10 秒钟。

关于java异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13817124/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com