How to distinguish programmatically between different IOExceptions?

9

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?

c#
exception-handling
ioexception
hresult
asked on Stack Overflow Jul 21, 2014 by ChaseMedallion

2 Answers

5

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;
        }
    }
}
answered on Stack Overflow Jul 22, 2014 by Hans Passant
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
}
answered on Stack Overflow Jul 22, 2014 by raney • edited Jul 22, 2014 by raney

User contributions licensed under CC BY-SA 3.0