How do I always get COMException instead of OutOfMemoryException?

十年热恋 提交于 2020-01-06 08:00:11

问题


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


来源:https://stackoverflow.com/questions/13682531/how-do-i-always-get-comexception-instead-of-outofmemoryexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!