我有一个套接字,我想发送消息并从中读取。
当我在另一端离线时使用套接字进行读/写时,我得到了相同的异常: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?
}
}
发布于 2019-05-14 03:03:04
是的,异常处理需要大量的资源,但有时也不是那么糟糕。
如果你只坚持一次try-catch,你可以检查错误消息。
注意:我还为一般(非IO)错误添加了第二个try-catch
try
{
SendData("!GetLocation!");
string data = GetData();
}
catch (System.IO.IOException ex)
{
if (ex.Message.IndexOf("Unable to read") != -1)
{
// GetData error
}
else if (ex.Message.IndexOf("Unable to write") != -1)
{
// SendData error
}
else
{
//Other IO errors
}
}
catch(Exception exc)
{
// Unspected errors
}
您还可以设置一个布尔变量并检查它的值,以了解它在哪里破坏了您的代码。
bool sendCalled = false;
try
{
SendData("!GetLocation!");
sendCalled = true;
string data = GetData();
}
catch (System.IO.IOException ex)
{
if (sendCalled)
{
// GetData error
}
else
{
// SendData error
}
}
https://stackoverflow.com/questions/56118266
复制相似问题