why i can't catch java.net.SocketTimeoutException?

Marwen Trabelsi picture Marwen Trabelsi · May 11, 2012 · Viewed 8.9k times · Source

I have a Simple Multithread Server, the code of Threads looks like this:

public void run(){

 while(Ecoute()){

     str=LireTrame(this.socClient);//read text byte by byte 

    //some code here

    Dormir(500);//Sleep for 500ms  
   }     


}

I'd like to create a timeout of 3 minutes, if a client socket does not send a message in 3 minutes, the thread must be closed...

so I try that:

 public void run(){

        try {
        socClient.setSoTimeout(180000);//timeout for 3 min...
    } catch (SocketException ex) {
        Logger.getLogger(tache.class.getName()).log(Level.SEVERE, null, ex);
    }


 while(Ecoute()){

     try{
      str=LireTrame(this.socClient);//read text byte by byte 
    }
    catch(java.net.SocketTimeoutException ex){
     log.append("timeout exception has benn catched \n") ;
     break;//break the while
   } 

    //some code here

    Dormir(500);//Sleep for 500ms  
   }     


}

the problem is that netbeans display an error message: enter image description here

java.net.SocketTimeoutException never thrown in body of corresponding try statement

I tried this with SocketException but same result..

why i can't catch them ?

UPDATE: based on responses from thinksteep and mprabhat, I added th throw in LireTrame(..) but still i can't catch the Exception:

 public  String LireTrame(Socket socClient) throws java.net.SocketTimeoutException{
 int c = 0;
  String Nmea="";
boolean finL=true;
 do{
            try {
                c=socClient.getInputStream().read();
            } catch (IOException ex) {
                Logger.getLogger(tache.class.getName()).log(Level.SEVERE, null, ex);
            }
    char ch=(char)c;

    Nmea=Nmea+ch;
    if(ch==';')
        finL=false;

  }while(finL);
 return Nmea;
 }



mai 11, 2012 8:04:02 PM Daemon.tache LireTrame
Grave: null
java.net.SocketTimeoutException: Read timed out
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.read(SocketInputStream.java:150)
    at java.net.SocketInputStream.read(SocketInputStream.java:121)
    at java.net.SocketInputStream.read(SocketInputStream.java:203)
    at Daemon.tache.LireTrame(tache.java:232)
    at Daemon.tache.run(tache.java:87)
    at java.lang.Thread.run(Thread.java:722)

are there any ideas to make this otherwise?

Answer

kosa picture kosa · May 11, 2012
=LireTrame(this.socClient);//read text byte by byte

should throw SocketTimeOutException. You didn't post code for this method, but I am assuming it is not throwing SocketTimeOutException which is why netbeans highlighting.