Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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?

like image 347
ChaseMedallion Avatar asked Jul 21 '14 23:07

ChaseMedallion


People also ask

What is the purpose of IOException?

IOException is the base class for exceptions thrown while accessing information using streams, files and directories. The Base Class Library includes the following types, each of which is a derived class of IOException : DirectoryNotFoundException. EndOfStreamException.

Which of the following handles IO errors?

System.IO.IOException Handles I/O errors.

Which of the following is IOException class?

IOException has subclasses such as FileNotFoundException , EOFException , UnsupportedEncodingException , SocketException , and SSLException . If the file is not found, FileNotFoundException is thrown.

Can error be handled in Java?

Recovering from Error is not possible. We can recover from exceptions by either using try-catch block or throwing exceptions back to the caller. All errors in java are unchecked type. Exceptions include both checked as well as unchecked type.


1 Answers

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;
        }
    }
}
like image 183
Hans Passant Avatar answered Oct 07 '22 16:10

Hans Passant