Java在特定调用上禁用堆栈跟踪?

时间:2013-05-09 19:47:45

标签: java exception timeout stack trace

我想禁用套接字超时产生的一条错误消息,因为它正在填充我的控制台(Linux,终端)。

代码:

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

   }
}

该程序正等待60秒才能得到任何响应。我在套接字上设置了超时,因为如果没有响应消息,while周期就会冻结。

错误:

  

java.net.SocketTimeoutException:接收超时时间   java.net.DualStackPlainDatagramSocketImpl.socketReceiveOrPeekData(母语   方法)在java.net.DualStackPlainDatagramSocketImpl.receive0(未知   来自java.net.AbstractPlainDatagramSocketImpl.receive(未知   来自)java.net.DatagramSocket.receive(未知来源)at   thread.ThreadListenResponseQuery.run(ThreadListenResponseQuery.java:46)     在java.lang.Thread.run(未知来源)

3 个答案:

答案 0 :(得分:2)

socket.receive try-catchtry { socket.receive() } catch (SocketTimeoutException e) { // Log an error, abort an communication, or just ignore }

{{1}}

答案 1 :(得分:1)

看看this

正如Alex W所写,可以在没有堆栈跟踪的情况下捕获Java中的Throwable对象:

 Throwable(String message, Throwable cause, boolean enableSuppression,boolean 
writableStackTrace) 

答案 2 :(得分:1)

如果你只是压制整个异常将让我们很难弄清楚究竟发生了什么。相反,我只打印一个日志输出,可能是这样的:

try {
   // invocation that throws the exception
} catch (SocketException e) {
   System.out.println(e.getMessage());
}