【发布时间】:2019-09-30 18:19:24
【问题描述】:
我有一个套接字,我想发送消息并从中读取。
当我在另一端离线时使用套接字读取/写入时,我得到相同的异常:System.IO.IOException: Unable to read data from the transport connection: Operation on non-blocking socket would block。
除了有两个单独的 try-catch 块之外,我如何确定它发生在两个中的哪一个?我不能在阅读超时结束后得到Timeout Exception 吗?
示例:
try
{
SendData("!GetLocation!");
string data = GetData();
}
catch (Exception ex)
{
if (ex is System.IO.IOException)
{
//How can I identify if the exception was raised at the read method or the write method?
}
}
【问题讨论】:
-
你所说的“发生在哪两个中”是什么意思?
-
为什么没有两个独立的 try-catch 块?
-
我可以,但这看起来不太好。我只是想进一步了解,我没有说没有它我就不会相处..
-
一个问题是您是否需要知道是哪一个引发了异常。你会做一些不同的事情吗?如果您确实需要区分两者,那么单独的尝试/捕获是要走的路。此外,您可以一次尝试多次捕获,而不是
if。首先捕获IoException,然后如果您需要捕获更一般的异常,请捕获Exception。通常我们需要的比我们想象的要少。有时我们在方法中不需要任何 try/catch,外部方法中的异常处理就足够了。
标签: c# sockets exception ioexception