i have two java classes running on different threads. one class makes a connection to the internet while the other class monitors the connection status. i want to throw an IOException incase the class making a connection delays while reading server response, at the sametime i dont want to throw an exception if there is some response being read from the Server.
i came up with this code.
my problem is i want to throw an IOException in class NetworkMonitor which will be caught by NetworkConnector class which is the main class. however the compiler complains of uncaught exception.
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.
}
}
}
//class that monitors if there a network activity occuring.
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();
}
}