用于套接字关闭的嵌套 IOException 捕获
我用以下方式写入套接字:
OutputStream socketStream = socket.getOutputStream();
socketStream.write(buf);
但这可能会抛出 IOException
,所以我这样做:
try {
OutputStream socketStream = socket.getOutputStream();
socketStream.write(buf);
} catch (IOException e) {
// logging
} finally {
socket.close();
}
但是
socket.close
也迫使我捕获IOException
!那么我需要在finally
中再次try ... catch
吗?当从
close
中捕获IOException
时,是否意味着套接字未关闭?那么再次尝试close?或者怎么办?
谢谢
I write to socket with:
OutputStream socketStream = socket.getOutputStream();
socketStream.write(buf);
But this can throw IOException
, so I do:
try {
OutputStream socketStream = socket.getOutputStream();
socketStream.write(buf);
} catch (IOException e) {
// logging
} finally {
socket.close();
}
But
socket.close
also force me to catchIOException
! So do I needtry ... catch
it again infinally
?When catch
IOException
fromclose
, it mean socket not closed? So tryclose
again? Or what to do?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
close()
会抛出IOException
,因为关闭某些内容通常意味着调用flush()
,并且刷新可能会失败。例如,如果您失去网络连接并发出socket.close()
,则无法刷新已缓冲的任何内容,因此flush()
将引发异常。由于数据可能会丢失,因此会检查异常,因此您必须处理这种可能性。我认为处理这个问题的最好方法是:
这段代码在常见情况下可以正常工作。如果出现问题(即使在
close()
内部),它将允许您捕获异常并在无条件关闭套接字并吞掉它可能抛出的所有内容之前执行某些操作。close()
throwsIOException
because closing something usually implies callingflush()
, and flushing might fail. For example, if you lose network connectivity and issuesocket.close()
, you cannot flush whatever you have buffered, soflush()
will throw an exception. Because data might be lost, the exception is checked, so you are forced to deal with that possibility.I think the best way to deal with this is:
This code will work normally in the common case. If something goes wrong (even inside
close()
), it will allow you to catch the exception and do something before unconditionally closing your socket and swallowing everything it might throw.close 抛出的异常通常可以被忽略(你可以记录它)。这与 C++ 中的析构函数中抛出异常几乎相同 - 您对此无能为力(通常无能为力),并且尝试再次关闭它是无意义的。清理抛出异常通常是糟糕的设计 - 您可以实现清理代码来进行清理,但这是一个递归问题,最终您只能这样做,除非您无法处理它。
The Exception thrown by close can usually just be ignored (well you can log it). That's pretty much the same as throwing an exception in a destructor in C++ - there's not much (usually nothing) you can do about it and trying to close it again is nonsensical. Cleanup throwing exceptions is usually bad design - you can implement cleanup code for the cleanup but that's a recursive problem, in the end you'll just have to except that you can't handle it.