How to handle WinRT exceptions that result in Exception?

后端 未结 1 1208
梦谈多话
梦谈多话 2021-02-09 08:19

If a Windows runtime type raises a COM error .NET seems to wrap this error often (or always?) just into an Exception instance. The error message includes the COM HR

1条回答
  •  执笔经年
    2021-02-09 09:26

    It is possible to catch Exception, handle particular errors by switching on the HRESULT, and re-throwing the Exception if the error was "unexpected." For example,

    try
    {
        // ...
    }
    catch (Exception ex)
    {
        switch (ex->HResult)
        {
        case E_INVALID_USER_BUFFER: // 0x800706f8
            // handle invalid buffer case...
            break;
        default:
            // Unexpected exception; re-throw:
            throw;
        }
    }
    

    (I would note that providing an invalid buffer sounds more like a logic error than a runtime error, so I wonder whether this particular exception should really be caught.)

    Alternatively, a more general solution would be to write a function or set of functions that handle Exception for known HRESULTs and re-throws a more specific exception. For example,

    static void HandleKnownExceptions(Action f)
    {
        try
        {
            f();
        }
        catch (Exception ex)
        {
            // Detect expected HRESULTs and throw the more-specific exception
            // type for each.
        }
    }
    

    Both of these approaches work equally well in both C++ and C#.

    Note that it isn't necessarily the case that Exception is thrown directly by the platform or other components. At the Windows Runtime ABI layer, there are no exceptions: all errors are reported across the ABI boundary by HRESULT. The CLR translates a handful of known HRESULTs to more specific exception types, but it cannot perform a general translation.

    0 讨论(0)
提交回复
热议问题