2013-05-09 112 views
0

我想禁用一個由套接字超時產生的錯誤消息,因爲它正在填充我的控制檯(Linux,終端)。Java在特定的調用中禁用堆棧跟蹤?

的代碼:

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: 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)

回答

2

環繞socket.receivetry-catch

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

看看this

書面由Alex W,有可能趕在Java中Throwable對象沒有一個堆棧跟蹤:

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

我已經嘗試過了,它不工作。 – 2013-05-09 19:50:12

+0

檢查編輯,希望它有幫助。 – 2013-05-09 19:55:30

1

如果只是抑制整個例外會讓真的很難搞清楚什麼是真正回事。相反,我只想打印日誌輸出可能是這樣的:

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