0

I want to disable one error message produces by a socket timeout, because it's filling my console (Linux, terminal).

The code:

public ThreadListenResponseQuery(DatagramSocket socket){
   this.socket = socket;
   try {
      socket.setSoTimeout(1500);
   } catch (SocketException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
   }
}

@Override
public void run(){
   System.out.println("Waiting for response...");

   // Waiting for 60 seconds...
   while(System.currentTimeMillis() < startTime + 60000){

      socket.receive(receive_packet);   
      // .. Additional work

   }
}

The program is waiting for 60 seconds to get any response. I am setting a timeout on the socket because the while cycle is freezing out if no response message is coming.

Error:

java.net.SocketTimeoutException: Receive timed out at java.net.DualStackPlainDatagramSocketImpl.socketReceiveOrPeekData(Native Method) at java.net.DualStackPlainDatagramSocketImpl.receive0(Unknown Source) at java.net.AbstractPlainDatagramSocketImpl.receive(Unknown Source) at java.net.DatagramSocket.receive(Unknown Source) at thread.ThreadListenResponseQuery.run(ThreadListenResponseQuery.java:46) at java.lang.Thread.run(Unknown Source)

Zbarcea Christian
  • 9,367
  • 22
  • 84
  • 137

3 Answers3

2

Surround socket.receive with try-catch:

try {
    socket.receive()
} catch (SocketTimeoutException e) {
    // Log an error, abort an communication, or just ignore
}
Maxim
  • 1,209
  • 15
  • 28
1

Take a look at this.

As written by Alex W, it's possible to catch a Throwable object in Java without a stack trace:

 Throwable(String message, Throwable cause, boolean enableSuppression,boolean 
writableStackTrace) 
Community
  • 1
  • 1
aran
  • 10,978
  • 5
  • 39
  • 69
1

If you just suppress the entire exception will let really hard to figure out what is really going on. Instead I would just print a log output that could be something like this:

try {
   // invocation that throws the exception
} catch (SocketException e) {
   System.out.println(e.getMessage());
}
Francisco Spaeth
  • 23,493
  • 7
  • 67
  • 106