简体   繁体   English

如何在不同的IOExceptions之间以编程方式区分?

[英]How to distinguish programmatically between different IOExceptions?

I am doing some exception handling for code which is writing to the StandardInput stream of a Process object. 我正在为写入Process对象的StandardInput流的代码执行一些异常处理。 The Process is kind of like the unix head command; 进程有点像unix head命令; 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. 但是,对我来说,如何将其与其他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. 我也可以使用HRESULT,但我找不到任何指定此HRESULT仅适用于此特定错误的文档。 What is the best way of doing this? 这样做的最佳方式是什么?

Use Marshal.GetHRForException() to detect the error code for the IOException. 使用Marshal.GetHRForException()来检测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. 这可以通过添加特定类型的catch块来实现。 Make sure you cascade them such that your base exception type IOException would catch last. 确保您级联它们,以便您的基本异常类型IOException将最后捕获。

try
{
    //your code here
}
catch (PipeException e)
{
    //swallow this however you like
}
catch (IOException e)
{
    //handle generic IOExceptions here
}
finally
{
    //cleanup
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM