How to distinguish programmatically between different IOExceptions?

独自空忆成欢 提交于 2019-12-05 03:22:37

Use Marshal.GetHRForException() to detect the error code for the IOException. Some sample code to help you fight the compiler:

using System;
using System.IO;
using System.Runtime.InteropServices;

class Program {
    static void Main(string[] args) {
        try {
            throw new IOException("test", unchecked((int)0x8007006d));
        }
        catch (IOException ex) {
            if (Marshal.GetHRForException(ex) != unchecked((int)0x8007006d)) throw;
        }
    }
}

This can be accomplished by adding specific typed catch blocks. Make sure you cascade them such that your base exception type IOException would catch last.

try
{
    //your code here
}
catch (PipeException e)
{
    //swallow this however you like
}
catch (IOException e)
{
    //handle generic IOExceptions here
}
finally
{
    //cleanup
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!