Cha*_*ion 9 c# exception-handling ioexception hresult
我正在为写入Process对象的StandardInput流的代码执行一些异常处理.进程有点像unix head命令; 它只读取部分输入流.当进程终止时,写入线程失败:
IOException
The pipe has been ended. (Exception from HRESULT: 0x8007006D)
Run Code Online (Sandbox Code Playgroud)
我想捕获这个异常并让它优雅地失败,因为这是预期的行为.但是,对我来说,如何将其与其他IOExceptions进行稳健的区分并不明显.我可以使用消息,但我理解这些是本地化的,因此这可能不适用于所有平台.我也可以使用HRESULT,但我找不到任何指定此HRESULT仅适用于此特定错误的文档.这样做的最佳方式是什么?
使用Marshal.GetHRForException()来检测IOException的错误代码.一些示例代码可以帮助您对抗编译器:
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)