如何在不同的IOExceptions的编程区别? [英] How to distinguish programmatically between different IOExceptions?

查看:239
本文介绍了如何在不同的IOExceptions的编程区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一些异常处理被写入Process对象的standardInput流代码。这个过程有点像UNIX head命令;它读取只属于它的输入流。当进程死亡,写入线程失败:

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)



我想捕获这个异常,并让它失败摆好,因为这是预期的行为。但是,这不是明显对我如何能稳健地从其他的IOExceptions区别开来。我可以使用的消息,但它是我的理解是,这些是局部的,因此,这可能无法工作在所有平台上。我还可以使用HRESULT,但我无法找到指定该HRESULT只应用于此特定错误的任何文件。什么是这样做的最佳方式?

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?

推荐答案

使用Marshal.GetHRForException()来检测IOException异常的错误代码。一些示例代码,以帮助你对抗编译:

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

这篇关于如何在不同的IOExceptions的编程区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆