Say I have a socket variable called SuperSocket is there any way that I can catch the timeout exception ?
       SuperSocket.setSoTimeout(5000);
       catch (SocketTimeoutException e){
        System.out.println("Timeout");
        System.exit(1);
    }
                As you may suspect based on the name, the SocketTimeoutException is thrown when a timeout occurs during a read or acceptance message within a socket connection.
socket timeout — a maximum time of inactivity between two data packets when exchanging data with a server.
You seem to not understand what setSoTimeout() does and when that exception would be thrown.
From the Javadoc: ( http://docs.oracle.com/javase/6/docs/api/java/net/Socket.html )
public void setSoTimeout(int timeout)
throws SocketExceptionEnable/disable SO_TIMEOUT with the specified timeout, in milliseconds. With this option set to a non-zero timeout, a read() call on the InputStream associated with this Socket will block for only this amount of time. If the timeout expires, a java.net.SocketTimeoutException is raised, though the Socket is still valid. The option must be enabled prior to entering the blocking operation to have effect. The timeout must be > 0. A timeout of zero is interpreted as an infinite timeout.
The only time a SocketTimeoutException can be thrown (and then caught) is when you're doing a blocking read on the Socket's underlying InputStream and no data is received in the specified time (causing the read to ... time out).
superSocket.setSoTimeout(5000);
InputStream is = superSocket.getInputStream();
int i;
try {
    i = is.read();
} catch (SocketTimeoutException ste) {
    System.out.println("I timed out!");
}
Edit to add: There's actually one other time the exception can be thrown, and that's if you're calling the two argument version of Socket.connect() where you supply a timeout. 
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With