2

When writing to an OutputStream it will throw a IOException exception if the remote machine down, or has disconnected. Now, I want to call a specific method when only (and only) the pipe is broken. The problem is that IOException does not have a code or errno property to check for this error. And the only way I was able to achieve this is by

        try {
            stream.write(message.getBytes("UTF8"));
            stream.flush();
        } catch (IOException e) {
            if (e.getMessage().equals("sendto failed: EPIPE (Broken pipe)")) {
                // perform a specific action
            } else {
                e.printStackTrace();
            }
        }

Obviously this is not the perfect way to achieve such a thing. Any suggestion for an efficient solution?

Emad Omar
  • 729
  • 9
  • 23

1 Answers1

1

As mentioned here

In Java, there is no BrokenPipeException specifically. This type of error will be found wrapped in a different exception, such as a SocketException or IOException.

So you can achieve the same using String#contains() method

if(e.getMessage().contains("Broken Pipe")){
// Do Whatever you want to do 
}
Community
  • 1
  • 1
Neeraj Jain
  • 7,643
  • 6
  • 34
  • 62