如何处理特定的IOException?

时间:2018-12-20 22:56:57

标签: c# serial-port ioexception

我有一个使用Socket和SerialPort的代码,我想处理特定的异常。使用Socket时,我没有问题,因为SocketException类具有SocketErrorCode,并且我在开关中使用它来处理错误,但是IOException类没有类似的东西。

是否有IOException类的例外列表?

try
{
    strTemp = "Command";
    fnWriteCommand(strTemp, communicationInterface);
    index = 10;
}
catch (SocketException socketEx)
{
    switch (socketEx.SocketErrorCode)
    {
        case SocketError.ConnectionRefused:
        case SocketError.ConnectionAborted:
        case SocketError.ConnectionReset:
        case SocketError.NotConnected:
            index = 0; // Restart sequence
            break;
        case SocketError.TimedOut:
            index = 10; // Retry
            break;
    }
}
catch (IOException IOEx)
{
    // Handle specific exceptions
}

2 个答案:

答案 0 :(得分:1)

System.IO.Ports.SerialPort类在操作系统System.IO.Ports.InternalResources的低级端口通信功能周围使用内部包装。

此模块处理I / O错误,并将其转换为托管System.IO.IOException。不幸的是,其中一些不使用数字错误代码,而只使用需要翻译的文本(资源标识符和中文翻译):

IO_PortNotFound "The specified port does not exist."
IO_PortNotFoundFileName "The port '{0}' does not exist."
IO_SharingViolation_NoFileName "The process cannot access the port because it is being used by another process."
IO_SharingViolation_File "The process cannot access the port '{0}' because it is being used by another process."

所有未映射到这四个异常字符串中任何一个的Winapi HREsult代码都将使用IOException和Windows API通过HResult API提供的文本转换为FormatMessage

IOException的许多子类中,在串行端口上下文中仅使用EndOfStreamException,可以专门捕获或查询它,如下所示:

if(IOEx is EndOfStreamException) 
{
    var eosex = IOEx as EndOfStreamException;
    ...
}

答案 1 :(得分:0)

IOException类具有引发的多个派生异常,这些异常提供有关遇到的IO错误的更多信息。您可以单独捕获这些:

try { // Some code }
catch (System.IO.DirectoryNotFoundException) { }
catch (System.IO.DriveNotFoundException) { }
catch (System.IO.EndOfStreamException) { }
catch (System.IO.FileLoadException) { }
catch (System.IO.FileNotFoundException) { }
catch (System.IO.InternalBufferOverflowException) { }
catch (System.IO.InvalidDataException) { }
catch (System.IO.PathTooLongException) { }
catch (System.IO.IOException) { // Something else happened. Check InnerException details }