How do I always get COMException instead of OutOfM

2019-09-09 08:20发布

问题:

My C# code consumes a COM object. Sometimes that COM object methods will return E_OUTOFMEMORY but it will get translated into System.OutOfMemoryException instead of System.Runtime.InteropServices.COMException with appropriate ErrorCode. This is a problem for me because it complicates my error handling - I'd prefer to have all error indications that arise from COM object methods being thrown as System.Runtime.InteropServices.COMException only.

Is it possible to always have System.Runtime.InteropServices.COMException and not System.OutOfMemoryException when a COM object method returns E_OUTOFMEMORY?

回答1:

It may be a bit of a cop-out, but why not wrap whatever code is throwing the System.OutOfMemoryException in a Try/catch and re-throw a System.Runtime.InteropServices.COMException?

Something along the lines of:

    try
        {
            // COM Code here
        }
        catch (System.OutOfMemoryException ex)
        {
            throw new System.Runtime.InteropServices.COMException("E_OUTOFMEMORY", ex);
        }