简体   繁体   中英

Handling java.net.SocketException

I have a program which sometimes encounters the errorjava.net.SocketException. Is there a way I can have the client program execute some code if (and only if) it encounters this error in order to "deal with" the error? The full error is

java.net.SocketException: Software caused connection abort: socket write error

Here's a summary of what I have now.

public void run()  {
    try {
        //some code that causes the SocketException 
    }

    catch (SocketException e) {
    System.out.println("I recognize the SocketException");
    }
}

However despite the error it still won't print the line.

Here is the full error

java.net.SocketException: Software caused connection abort: socket write error
    at java.net.SocketOutputStream.socketWrite0(Native Method)
    at java.net.SocketOutputStream.socketWrite(Unknown Source)
    at java.net.SocketOutputStream.write(Unknown Source)
    at java.io.ObjectOutputStream$BlockDataOutputStream.drain(Unknown Source)
    at java.io.ObjectOutputStream$BlockDataOutputStream.setBlockDataMode(Unknown Source)  
    at java.io.ObjectOutputStream.writeNonProxyDesc(Unknown Source)
    at java.io.ObjectOutputStream.writeClassDesc(Unknown Source)
    at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
    at java.io.ObjectOutputStream.writeObject0(Unknown Source)
    at java.io.ObjectOutputStream.writeFatalException(Unknown Source)
    at java.io.ObjectOutputStream.writeObject(Unknown Source)
    at (...).java:61)
    at (...).java:164)

It depends on whether the client or the server is the one throwing the exception.

Either way, you should just be able to add a try-catch block around the code.

try {
   //code
} catch (SocketException e) {
   // Handle the error
}

If the server is throwing the error and you want the client to handle the situation, the client should be throwing an exception due to the loss of connection (this is what this exception looks like). Alternatively, if the server throws an error but doesn't crash, just have the server send some signal to the client that an error occurred.

Either way, with a little more information, I could give you a better resposne.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM