仅在抛出IOException时检查Broken Pipe

时间:2015-04-01 11:58:04

标签: java android ioexception broken-pipe

写入OutputStream时,如果远程计算机已关闭或已断开连接,则会抛出IOException异常。现在,我想在仅(并且仅)管道损坏时调用特定方法。问题是IOException没有codeerrno属性来检查此错误。我能够实现这一目标的唯一方法是

        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();
            }
        }

显然,这不是实现这一目标的完美方式。有任何建议可以提供有效的解决方案吗?

1 个答案:

答案 0 :(得分:1)

As mentioned here

  

在Java中,没有具体的BrokenPipeException。这类   错误将被包含在一个不同的异常中,例如a   SocketExceptionIOException

因此,您可以使用String#contains()方法

实现相同目标
if(e.getMessage().contains("Broken Pipe")){
// Do Whatever you want to do 
}