How to distinguish programmatically between different IOExceptions?

北城余情 提交于 2019-12-22 04:09:26

问题


I am doing some exception handling for code which is writing to the StandardInput stream of a Process object. The Process is kind of like the unix head command; it reads only part of it's input stream. When the process dies, the writing thread fails with:

IOException
The pipe has been ended. (Exception from HRESULT: 0x8007006D)

I would like to catch this exception and let it fail gracefully, since this is expected behavior. However, it's not obvious to me how this can robustly be distinguished from other IOExceptions. I could use message, but it's my understanding that these are localized and thus this might not work on all platforms. I could also use HRESULT, but I can't find any documentation that specifies that this HRESULT applies only to this particular error. What is the best way of doing this?


回答1:


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;
        }
    }
}



回答2:


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
}


来源:https://stackoverflow.com/questions/24876580/how-to-distinguish-programmatically-between-different-ioexceptions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!